Skip to content

Instantly share code, notes, and snippets.

@gergob
gergob / terminal.py
Last active August 29, 2015 14:14
Colorful console in Python
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()
@gergob
gergob / login.py
Last active August 29, 2015 14:13
@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():
# 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
{% 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 %}
from flask import Flask
# initialize a new Flask app
app = Flask(__name__)
# add one routing
@app.route("/")
def index():
return "Homepage routing works!"
# 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)
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
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(",")]
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
@gergob
gergob / main.py
Last active March 30, 2019 01:21
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