Flask and SQLAlchemy explained

Awesome explanation of SQLAlchemy with examples and comparison to Django by Armin Ronacher: SQLAlchemy and You Flask-SQLAlchemy module Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. How to add SQLAlchemy to Flask application: from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # configuration of the DB is read from flask configuration storage app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' # here we define db object that keeps track of sql interactions db = SQLAlchemy(app) Now we are ready to define tables and objects using predefined db....

January 11, 2018 · SergeM

Sample project with Ember and Flask

I want to use EmberJS with Flask application. Flask will provide an API. Ember frontend will consume and display data from the Flask backend. Let’s say we want our fronted to display a list of users of the system. We will have a main page and users page in our frontend. On the users page the client will see a list of users that we get from backend. Source code is here: ember_flask_example...

October 25, 2017 · SergeM

Correct way of running long tasks in Flask

Key to the answer is Celery. Good post: Using Celery With Flask Sources See also: Making an asynchronous task in Flask Sharing memory and using multiprocessing along with gunicorn seem to be wrong solutions.

January 23, 2017 · SergeM

Testing json responses in Flask REST apps with pytest

Testing is an essential part of software developmnet process. Unfortunately best prictives for python are established not as good as for example in Java world. Here I try to explain how to test Flask-based web applications. We want to test endpoints behaviour including status codes and parameters encoding. It means testing of handler functions for those endpoints is not enough. Tests for endpoints can be considered/used as high-level acceptance tests....

November 27, 2016 · SergeM

Python logging best practices

Python has a great built-in logging library. It allows to avoid a lot of boilerplate code and provides great features. Here are some examples. Logging allows to set up a unified formatting for logs: 2023-10-03 12:57:22,377|classifier.py| 62|522130|MainThread|INFO|Classifying messages from ./messages.ndjson (images ./save_path)... 2023-10-03 12:57:22,378|classifier.py| 44|522130|MainThread|INFO|Start reading input messages from ./messages.ndjson 2023-10-03 12:57:22,378|classifier.py| 48|522130|MainThread|INFO|Loaded event {'id': 104162, 'date': '2023-09-27T07:12:08+00:00', 'entities': []} 2023-10-03 12:57:22,378|classifier.py| 48|522130|MainThread|INFO|Loaded event {'id': 58934, 'date': '2023-09-27T07:12:09+00:00', 'entities': [{'_': 'MessageEntityBold', 'offset': 92, 'length': 8}]} 2023-10-03 12:57:22,378|classifier....

April 21, 2015 · SergeM