Instantly share code, notes, and snippets.

View terminal.py
from blessings import Terminal
if __name__ == "__main__":
# create a new instance of Terminal class
terminal = Terminal()
print("Your terminal supports {0} different colors.\n".format(terminal.number_of_colors))
indentation = 3 * terminal.move_right()
View login.py
@app.route("/")
@user_login_needed
def index():
return render_template("index.html")
return user_login_needed(index) # no extra parameters passed since index does not take any parameters
@app.route("/login", methods=["GET", "POST"])
def login():
View user_login_needed.py
# decorator for Flask application methods
def user_login_needed(f):
@wraps(f)
def decorated_function(*args, **kwargs):
is_user_logged_in = session['user_logged_in']
if not is_user_logged_in:
return redirect(url_for('login'))
else:
return f(*args, **kwargs)
return decorated_function
View contacts_template.html
{% extends "index.html" %}
{% block title %}Contacts{% endblock %}
{% block content %}
<h2>Contacts</h2>
{% if contacts %}
<p>There are {{ contacts | length }} contacts in the database.</p>
{% if contacts|length > 0 %}
View simple_flask_app.py
from flask import Flask
# initialize a new Flask app
app = Flask(__name__)
# add one routing
@app.route("/")
def index():
return "Homepage routing works!"
View manipulating_strings.py
# string declaration
my_str1 = 'simple text'
my_str2 = "simple text 2"
my_multiline_str = """Hey, this
is a multiline
string in python"""
my_unicode_str = "This is a unicode string containing some special characters like:éáő"
print(my_str1)
View count_words.py
def count_words(text):
"""Makes a statistic of the words appearing in the text
and returns a dictionary where keys are the words and
values are the number of occurrence of each word."""
words = text.split()
result = {}
for word in words:
if word in result:
result[word] += 1
View parse_csv.py
def parse_csv(text):
"""Parses a CSV format text, returns a dictionary, keys are the Column headers from the CSV and values are the data"""
result = {}
# first split by EOL
lines = text.split("\n")
if len(lines) > 0:
headers = [item.strip() for item in lines[0].split(",")]
View pymongo_output.txt
greg@earth ~/Development/_freelancer/crud_operations_in_mongodb_using_python $ python main.py
Loading all items from database:
ID = 54953f0a8524880d021cd856 | Title = Wordpress website for Freelancers | Price = 250
ID = 54953f408524880d0db9a8a1 | Title = Wordpress website for Freelancers | Price = 250
ID = 54953f788524880d14d4e590 | Title = Wordpress website for Freelancers | Price = 250
Saving new_project to database
new_project saved to database
View main.py
from projects_repository import ProjectsRepository
from project import Project
def load_all_items_from_database(repository):
print("Loading all items from database:")
projects = repository.read()
at_least_one_item = False
for p in projects:
at_least_one_item = True