analitics

Pages

Monday, August 5, 2019

Python 3.7.3 : Using the flask - part 009.

In this tutorial, I will show you how to use blueprints with a new type of flask project using multiple python files.
I show you just how to create the A.P.I. not the REACT front end.
Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications. A Blueprint object works similarly to a Flask application object, but it is not actually an application. Rather it is a blueprint of how to construct or extend an application., see the official webpage.
In my my_flask folder, I create a blue_test folder with three python files: __init__.py, views.py, and models.py.
The __init__.py file has this source code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# create path for SQLAlchemy
import os
basedir = os.path.abspath(os.path.dirname(__file__))

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    # instantiate config for SQLAlchemy
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'texts.sqlite')
    # init db 
    db.init_app(app)
    # avoid circular importing of circular dependency 
    from .views import main
    app.register_blueprint(main)
    return app
The views.py come with this source code:
from flask import Blueprint
from flask import jsonify, request
from . import db
from .models import Texts

main = Blueprint('main', __name__)
@main.route('/add_text', methods = ['POST'])
def add_text():
    txt_data = request.get_json()
    new_txt = Texts(title=txt_data['title'], txt_content=txt_data['txt_content'])
    db.session(new_txt)
    db.session.commit()
    # 201 status code for create successfully
    return 'Done', 201
@main.route('/texts/')
def texts():
    txt_list=Texts.query.all()
    texts=[]
    for txt in txt_list:
        texts.append({'title': txt.title, 'txt_content':txt.txt_content})
    return jsonify ({'texts':texts})
The models.py has this source code:
# import db from base folder, see dot
from . import db 

class Texts(db.Model):
    # primary key 
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    txt_content = db.Column(db.String(1000))
Use the base folder of the blue_test folder to instantiate the database named texts.sqlite with a table texts.
C:\Python373>cd my_flask

C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from blue_test.models import Texts
>>> from blue_test import db, create_app
>>> db.create_all(app=create_app())
>>> exit()
If not run into the base folder then you get this error:
    from . import db
ImportError: attempted relative import with no known parent package
Now you will have a texts.sqlite file for the database.
Use this command to set FLASK_APP:
C:\Python373\my_flask>set FLASK_APP=blue_test
C:\Python373\my_flask>flask run
Now, using the postman you can test it by running the python script and call these methods.



Sunday, August 4, 2019

Python 3.7.3 : Using the flask - part 008.

The tutorial for today will show you how to understand the flash method and fix exceptions.
First, the Flask module contains a flash method which passes a message to the next request, which generally is a template.
This lets you create feedback to users of a web application is critical, from notifications and error messages to warnings and progress alerts.
This system allows us to record a message at any point within a request, then display it at the start of the next request (and only the next request), see the documentation.
You need to import the flash with:
from flask import flash
The flash function takes up to 2 arguments, a message and a category like this: flash("message", "category").
In the next example, the random range output named out will send a flash message by category.
The flash warning category will send the number get by the random and will be into a range of 1 and 3.
Flashed messages are stored in the session until they are read it.
The HTML5 page named home.html can be found at my GitHub project.
This source code will send one message by flash and show two messages into a webpage.
@app.route('/',methods = ['GET','POST'])
def home():
    # test flash message
    out = random.randint(1,10)
    if out in range(1,3):
        flash(str(out),"warning" )
    if out in range(4,6):
        flash("This is a flash test for home.html with result:","success")
    if out in range(7,10):
        flash("This is a flash test for home.html with result:","danger")  
    return render_template("home.html")
The next example shows you how to use flash and exceptions to create an output error with render_template_string.
The output exception sends by flash without an HTML5 page request.
from flask import render_template_string
...
# fix Exception error , like 404
@app.errorhandler(Exception)
def page_not_found(e):
    flash(e, type(e))  
    return render_template_string('''
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          {% set printed_messages = dict() %}
          {% for category, message in messages %}
            {% if message not in printed_messages %}
              
{{message}}
{% set x = printed_messages.__setitem__(message, "value") %} {% endif %} {% endfor %} {% endif %} {% endwith %} ''')
If you put a bad path URL intro the server ( http://127.0.0.1:5000/bad ) then you get the result of the exception 404:
404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Using the flash you can create your own notification system.

Saturday, August 3, 2019

Python 3.7.3 : Using the flask - part 007.

This will be a long tutorial because will try to link some information's from the last tutorials.
First, the structure of the project can see into my GitHub project.
I create new templates and another python script named tserv.py for testing.
You can see easier how the POST method works and how to deal with a python database issue.
This script comes with an upload file feature and upload database with sqlite3 python module.
First, for upload a file we need the HTML5 file from templates folder named upload.html.
I update the base.html file to use the bootstrap framework.
import sqlite3
class UploadForm(FlaskForm):
    file = FileField()
    submit = SubmitField("submit")
    
@app.route('/upload',methods = ['GET','POST'])
def upload():
    form = UploadForm()
    
    if request.method == "POST" and form.validate():
        if form.validate_on_submit():
            file_name = form.file.data
            file_database(name = file_name.filename,data = file_name.read())
            print("File {}".format(file_name.filename))
            return render_template("upload.html", form = form)
    return render_template("upload.html", form = form)
def file_database(name,data):
    con=sqlite3.connect("file_upload.db")
    cursor = con.cursor()
    cursor.execute("""CREATE TABLE IF NOT EXISTS my_table (name TEXT, data BLOP) """)
    cursor.execute("""INSERT INTO my_table (name , data ) VALUES (?,?) """, (name, data))
    con.commit()
    cursor.close()
    con.close()
Let's run it:
python tserv.py
Into the main folder a database will be create and will fill with the file uploaded.
Now, if you want to add more we can create a download button into our UploadForm, is no need to have another python class.
First create your form tag into upload.html file and link with the python tserv.py code show bellow:
from flask import send_file
from io import BytesIO
...
@app.route('/download', methods=['GET','POST'])
def download():
    form = UploadForm()
    if request.method == "POST":
        con = sqlite3.connect("file_upload.db")
        cursor = con.cursor()
        cur_ex = cursor.execute(""" SELECT * FROM my_table """)
        for i in cur_ex.fetchall():
            name=i[0]
            data=i[1]
            break
        con.commit()
        cursor.close()
        con.close()
        return send_file(BytesIO(data), attachment_filename='test', as_attachment=True)
    return render_template("home.html", form = form)
When you run it the download button will download the first file upload into database.
This example tutorial can be more complex.
For example, you can show the database content into a new HTML file and then save with an open dialog to disk.

Friday, August 2, 2019

Python 3.7.3 : Using the flask - part 006.

Today I will show you how to use the RESTful API application with flask python module that uses HTTP requests to GET, PUT, POST and DELETE data.
When HTTP is used, as is most common, the operations (HTTP methods) available are GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS and TRACE.[2], see the Wikipedia article.
All of these HTTP methods will be tested with postman software.
You need to have an account and use the downloaded software in order to interrogate with these methods.
Let's see the source new code first:
@app.route("/users/", methods=['GET'])
def users():
    users = User.query.all()
    #return users_schema.jsonify(users)
    all_users = users_schema.dump(users)
    return jsonify(all_users.data)

@app.route("/users/", methods=['POST'])
def user_post(id):
    user_post = User.query.get(id)
    print(user_post)
    username = request.json['username']
    email = request.json['email']
    user_post.username = username
    user_post.email = email
    db.session.commit()
    return user_schema.jsonify(user_post)

@app.route("/users/", methods=['PUT'])
def user_put(id):
    user_put = User.query.get(id)
    print(user_put)
    username = request.json['username']
    email = request.json['email']
    user_put.username = username
    user_put.email = email
    db.session.commit()
    return user_schema.jsonify(user_put)

@app.route("/users/", methods=['DELETE'])
def user_delete(id):
    user_delete = User.query.get(id)
    print(user_delete)
    db.session.delete(user_delete)
    db.session.commit()
    return user_schema.jsonify(user_delete)
Using the postman you can test it by running the python script and call these methods at http://127.0.0.1:5000/users/.

Thursday, August 1, 2019

Python 3.7.3 : Using the flask - part 005.

In the last tutorial, I used the flask-sqlalchemy python module.
Today I will show you how to use the flask_marshmallow python module.
First, let's take a look at this python module, see the official webpage:
Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.
The base class User will need to be integrated with this python module:
from flask import Flask
from flask import render_template
from forms import SignUpForm
from flask import request

from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
from forms import AddUser

app = Flask (__name__)
app.config['SECRET_KEY'] = 'abcdefg'
# set SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'server.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email
    '''
    def __rep_(self):
        return '' % self.username
    '''
class UserSchema(ma.ModelSchema):
    class Meta:
        model = User
user_schema = UserSchema()
users_schema = UserSchema(many=True)

@app.route("/users/", methods=['GET'])
def users():
    users = User.query.all()
    #return users_schema.jsonify(users)
    all_users = users_schema.dump(users)
    return jsonify(all_users.data)

# the default name main
if __name__ == '__main__':
    app.run(debug=True)
Let's take a look at http://127.0.0.1:5000/users/ and see the result:
[
  {
    "email": "catafest@yahoo.com", 
    "id": 1, 
    "username": "catafest"
  }, 
  {
    "email": "test@test.com", 
    "id": 2, 
    "username": "user_test"
  }
]

Tuesday, July 30, 2019

Python 3.7.3 : Using the flask - part 004.

The goal of this tutorial is to interact with the database in order to use it with flask_sqlalchemy python module.
The db.Model is used to interact with the database.
A database doesn't need a primary key but if you using the flask-sqlalchemy you need to have it for each one table in order to connect it.
Let's see the database:
C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import db
>>> db.create_all()
>>> db.engine.table_names()
['user']
Let's add some data into database on user table:
C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import db
>>> from server import User
>>> first_user = User(username='catafest',email='catafest@yahoo.com')
>>> db.session.add(first_user)
>>> db.session.commit()
>>> test_user = User(username='test',email='test@test.com')
>>> db.session.add(test_user)
>>> db.session.commit()
Update is a simple issue.
Let's update the username test_user from test to user_test:
>>> test_user.username = 'user_test'
>>> db.session.commit()
The delete is simple like the add:
>>> db.session.delete(test_user)
>>> db.session.commit()
Let's use query:
>>> results=User.query.all()
>>> results[0].username
'catafest'
>>> results[0].email
'catafest@yahoo.com'
>>> results
The next step is an important issue because let you to see how result by content and query and filter by first result:
>>> q1 = User.query.filter_by(username='catafest')
>>> q1
...flask_sqlalchemy .basequery= ...
>>> print(q1)
SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email
FROM user
WHERE user.username = ?
>>> q2 = User.query.filter_by(username='catafest').first()
>>> q2
< User 1 >
>>> print(q2)
< User 1 >
>>> print(q1.username)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'BaseQuery' object has no attribute 'username'
>>> print(q2.username)
catafest
>>> print(q2.username,q2.email)
catafest catafest@yahoo.com 
In this case because the first is limited to one result the print of q2 is the correct way.

Monday, July 29, 2019

Python 3.7.3 : Using the twitter python module - part 003.

Today I will speak about twitter python module with the new changes of the A.P.I.
This two tutorial will not work now because the twitter A.P.I is changed.
The reason I don't delete it is the similar flow programming and access the A.P.I.:
Let's start with the install of this python module with Python version 3.7.3:
C:\Python373>cd Scripts

C:\Python373\Scripts>pip install python-twitter
...
Installing collected packages: python-twitter
Successfully installed python-twitter-3.5
Let's test the GetSearch.
You need to create a twitter application to have access to the tokens and secret keys:
import os
import json
import twitter
from twitter import *
CONSUMER_KEY=""
CONSUMER_SECRET=""

ACCESS_TOKEN=""
ACCESS_TOKEN_SECRET=""
LANGUAGES="En"
at=input("ACCESS_TOKEN: ", )
ats=input("ACCESS_TOKEN_SECRET: ", )
ck=input("CONSUMER_KEY: ", )
cs=input("CONSUMER_SECRET: ", )
api = Api(ck, cs, at, ats)
def main():
    print("Search by query using the GetSearch ")
    r = api.GetSearch(raw_query="q=twitter%20&result_type=recent&since=1999-03-07&count=100")
    print(r)
if __name__ == '__main__':
    main()
The result will be something like this:
...
@GeorgePapa19 @realDonaldTrump Sure Did https://t.co/GblrSOsaJg'), Status(ID=115
5787444525993984, ScreenName=MD__PCY, Created=Mon Jul 29 10:29:34 +0000 2019, Te
xt='mal ako ni twitter https://t.co/lRA1BOyf6a'), Status(ID=1155787444517838849,
 ScreenName=Elyse95, Created=Mon Jul 29 10:29:34 +0000 2019, Text='????? ????? ?
??? ..??? ???? ????????? ????? ????? ????? ?????? ??? ???????? .. !!    ... http
s://t.co/weChoAPDnC. https://t.co/34D2nmtbOz'), Status(ID=1155787444517781504, S
creenName=chrichacham123, Created=Mon Jul 29 10:29:34 +0000 2019, Text='RT @John
JCrace: Project Blind Faith! https://t.co/2mpB0MC540'), Status(ID=11557874445134
72514, ScreenName=318520_mu, Created=Mon Jul 29 10:29:34 +0000 2019, Text='31-85
20 ????????\n???????? → ???twitter??????????????\n??...?\n\nhttps://t.co/oVET5Z9
wXq')]

Sunday, July 28, 2019

Python 3.7.3 : Using the flask - part 003.

Another tutorial with python 3.7.3 and flask python module.
In the last tutorial, I speak about some tricks and tips.
Today, I will show some steps for fixing and run with flask-sqlalchemy.
The source code from my GitHub account can be updated with this source code.
app = Flask (__name__)
app.config['SECRET_KEY'] = 'abcdefg'
# set SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'server.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email
If you run it then you get this:
C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import db
C:\Python373\lib\site-packages\flask_sqlalchemy\__init__.py:835: FSADeprecationW
arning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be dis
abled by default in the future.  Set it to True or False to suppress this warnin
g.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
You will have a database file named server.sqlite.
#app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
Let's create and show the database:
C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import db
>>> db.create_all()
>>> db.engine.table_names()
['user']
A good approach is to create a config.py file and used into the application area.
The config.py file will have this source code:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'server.sqlite')
DEBUG=True
The server.py has this source code:
...
app = Flask (__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
...

Saturday, July 27, 2019

Python 3.7.3 : About pytweening python module.

This is a simple module of tweening and easing functions implemented in Python, see the GitHub webpage.
C:\Python373\Scripts>pip install pytweening
Collecting pytweening
Downloading https://files.pythonhosted.org/packages/b9/f8/c32a58d6e4dff8aa5c27
e907194d69f3b57e525c2e4af96f39c6e9c854d2/PyTweening-1.0.3.zip
Building wheels for collected packages: pytweening
Building wheel for pytweening (setup.py) ... done
Created wheel for pytweening: filename=PyTweening-1.0.3-cp37-none-any.whl size
=3821 sha256=6655c055d779982ff1259a5266bf1300c1cd02046e45e92cf18b20053a326531
Stored in directory: C:\Users\catafest\AppData\Local\pip\Cache\wheels\7b\92\30
\06e21159eed2709436bfb6d7c690959e578cf74f029643866e
Successfully built pytweening
Installing collected packages: pytweening
Successfully installed pytweening-1.0.3
Let's test it:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pytweening
>>> dir(pytweening)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__path__', '__spec__', '__version__', '_checkRange', 'division',
 'easeInBack', 'easeInBounce', 'easeInCirc', 'easeInCubic', 'easeInElastic', 'ea
seInExpo', 'easeInOutBack', 'easeInOutBounce', 'easeInOutCirc', 'easeInOutCubic'
, 'easeInOutElastic', 'easeInOutExpo', 'easeInOutQuad', 'easeInOutQuart', 'easeI
nOutQuint', 'easeInOutSine', 'easeInQuad', 'easeInQuart', 'easeInQuint', 'easeIn
Sine', 'easeOutBack', 'easeOutBounce', 'easeOutCirc', 'easeOutCubic', 'easeOutEl
astic', 'easeOutExpo', 'easeOutQuad', 'easeOutQuart', 'easeOutQuint', 'easeOutSi
ne', 'getLine', 'getPointOnLine', 'linear', 'math']
>>> pytweening.linear(0.1)
0.1
>>> pytweening.easeInOutSine(0.1)
0.024471741852423234
>>> pytweening.easeInQuad(0.1)
0.010000000000000002
>>> pytweening.getLine(0, 0, 0.1, 0.1)
[(0, 0)]
>>> pytweening.getLine(0, 0, 1.1, 1.1)
[(0, 0), (1, 1)]
For example, this module can help with some math function:
  • simple linear tweening - no easing, no acceleration;
  • quadratic easing in/out - acceleration until halfway, then deceleration;
  • cubic easing in/out - acceleration until halfway, then deceleration;
  • quartic easing in/out - acceleration until halfway, then deceleration;
  • sinusoidal easing in/out - accelerating until halfway, then decelerating;
  • ...

Friday, July 26, 2019

Python 3.7.3 : Tonny I.D.E. for python programmers.

Today I tested the Thonny I.D.E. from thonny.org official webpage.
Yesterday I tried several editors for python programming language and did not work.
One of these is the spyder editor that does not work with python 3.7.3 - we have not discovered why.
The Mu is a simple Python editor for beginner programmers and has a strange working I.D.E. for good and fast development.
The PyCharm, it is developed by the Czech company JetBrains is not fully free ...

The Thonny I.D.E. is fast and comes with two good features:
Code completion and Highlights syntax errors.
The install steps are easy with a wizard application.
After that, you can test with any python source code.
The source code from the image is a simple example from this webpage.
Let's see a screenshot:

This is a video tutorial with this I.D.E. from Aivar Annamaa user:



Thursday, July 25, 2019

Python 3.7.3 : Using the flask - part 002.

Let's see some tips for starting any project with flask python module.
Use these python modules to work with databases: flask-sqlalchemy and flask_marshmallow.
The Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application.
The marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes.
Let's install it:
C:\Python373>cd Scripts

C:\Python373\Scripts>pip install flask-sqlalchemy
Collecting flask_sqlalchemy
...
Successfully installed flask-sqlalchemy-2.4.0
C:\Python373\Scripts>pip install flask_marshmallow
Collecting flask_marshmallow
...
Successfully installed flask-marshmallow-0.10.1 marshmallow-2.19.5
C:\Python373\Scripts>pip install marshmallow-sqlalchemy
Collecting marshmallow-sqlalchemy
...
Successfully installed marshmallow-sqlalchemy-0.17.0
Use these python modules for login and authorization issues: flask-login
The Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering your users’ sessions over extended periods of time.
Flask-login doesn't actually have a user backend, it just handles the session machinery to help you to log in and logout users.
Flask-Login can work with user models that are based on any database system with four required items: is_authenticated, is_active, is_anonymous and get_id.
Let's install it:
C:\Python373\Scripts>pip install flask-login
Collecting flask-login
...
Successfully installed flask-login-0.4.1
This python module named python-dotenv let us to reads the key-value pair from .env file and adds them to an environment variable.
C:\Python373\Scripts>pip install python-dotenv
Collecting python-dotenv
...
Successfully installed python-dotenv-0.10.3
Flask-Login provides a UserMixin which makes it easy to create a user class, see example class User:
from flask_login import UserMixin
...
class User(UserMixin, db.Model):
Another tip is to use the get_or_404 and first_or_404 to avoid show errors on the webpage.
Reduce the passing of multiple variables to render_template, let's see the example:
from flask import render_template
...
return render_template('index.html', fn=name.first, ln=name.last, day=student.day, 
.... ')
This can de easy fix with this code to send value I want to pass:
context = {
'fn': name.first,
'ln': name.last,
'day': student.day,
...
}
return render_template('index.html', **context)
Use query to solve complex tasks.
Let's see a simple example of delete from a Student database class:
...
class Student(db.Model):
id=db.Column(db.Integer, primary_key=True)
...
country=db.Column(db.String(2))
...
Let's delete this with a query and return the number of deleted by delete_count:
del_ids= db.session.query(Student.id).filter(Student.country=='Ro')
delete_count=db.session.query(Student).filter(Student.id.in_(del_ids.subquery())).delete(synchronize_session=False)
I used two files in the main project named .env and .flaskenv:
The file .env comes with:
SQLALCHEMY_DATABASE_URI=sqlite:///db.sqlite3
SECRET_KEY = abcdef
The file .flaskenv has these lines of source code:
FLASK_ENV = development
FLASK_APP = my_flask_app
This can be used into a new file named settings.py:
import os 
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI')
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_TRACK_MODIFICATIONS = False
Using this the main flask application will start like this:
from flask import Flask
def create_my_app(config_file='settings.py'):
    app = Flask(__name__)
    app.config.from_pyfile(config_file)
    return app
There are plenty of tips and tricks that can be found based on the project in the bottle.
These are the most used.


Wednesday, July 24, 2019

Python 3.7.3 : Testing the timeit and Bokeh python module.

The tutorial today has several goals:
  • testing the timeit function to measure the execution time of a line of print code;
  • using python lists to record data;
  • generate lists using the range function;
  • multiplying a number with an entire list of numbers;
  • how to use the bokeh module with CustomJSHover and HoverTool
Let's test with the timeit python module, see the official webpage.
This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> import random
>>> timeit.timeit('print("a")',number=1)
a
0.00013114200010022614
>>> timeit.timeit('print("a")',number=100)
...
a
0.007177434000027461
>>> timeit.timeit('print("a")',number=1000)
...
a
0.07585798000002342
Let make more visible the results with the bokeh python module:
import timeit
import random

# if you want to use numpy 
#import numpy as np

# import bokeh python module 
from bokeh.plotting import figure, show, output_file
# for show values
from bokeh.models.tools import CustomJSHover
from bokeh.models import HoverTool
print ('''
You can tests a number of times named l
with a number of print named i
and see the result value with bokeh python module
timeit.timeit('print("a")',number = i)
''')
i = int(input('The increment number i:'))
l = int(input('The number of test l:'))

# create the list with the output values
timit_list = []
# create the test function for l and i and return the list
def get_timeit(i,l):
 while i < l:
  i += 1
  out=timeit.timeit('print("a")',number = i)
  timit_list.append(out)
 return timit_list

# run the test function with l and i
# this will be coordinate y
yt=get_timeit(i,l)

# show result of the test 
print(yt)

# create the coordinate x
xt = [i for i in range(0, len(yt))]

#xt = np.linspace(0, l, l)
# print the coordinate x
#print(xt)

# create the output HTML file to see the result
output_file("test.html")

# create a figure with a timeit type y-axis
fig = figure(title='timit_list values for print("a")',
             plot_height=400, plot_width=700,
             x_axis_label='x has each incrementation of i', y_axis_label='value of timeit of print the char a',
             x_minor_ticks=3, 
             toolbar_location=None)

# create a circle for each value
# see new multiplication with a list 
# y=[i * 100 for i in yt]
fig.circle(x=xt, y=[i * 100 for i in yt], 
         color='blue', size=5,
         legend='Values')

x_custom = CustomJSHover(code="""
    return '' + special_vars.data_x""")

y_custom = CustomJSHover(code="""
    return '' + special_vars.data_y""")

fig.add_tools(
    HoverTool(
        show_arrow=True, 
        tooltips=[
 ('xt', '$data_x'),
 ('yt', '$data_y')
        ],
        formatters=dict(
            xt=x_custom,
            yt=y_custom
        )
    )
)

# Put the legend in the upper left corner
fig.legend.location = 'top_left'

# Let's check it out
show(fig)
The result of this python source code can be found on my YouTube channel:


Tuesday, July 23, 2019

Python 3.7.3 : Using the flask - part 001.

A short intro into this python module can be found at the PyPI website:
Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

Flask offers suggestions but doesn’t enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that makes adding new functionality easy.

The reason I used a series of tutorials with this python module is the complexity of the features of this python module.
Let's briefly outline some of the essential aspects of flask programming.
  • Flask is a simple, lightweight, and minimalist web framework;
  • Flask is developed based on the Jinja2 template engine;
  • Flask depends on the Jinja template engine and the Werkzeug WSGI toolkit;
  • Flask does not provide a built-in ORM system (Object Relation Mapping);
  • in Flask web applications to perform CRUD operations on a database can be tedious (see: ORM techniques of Flask-SQLAlchemy);
  • The Flask has a simple and customizable architecture;
  • the Flask to accelerate the development of simple websites that use static content;
  • has the option to extend and customize Flask according to precise project requirements;
A list of companies using the Flask framework - who is using Flask?
The install process is very simple using the pip tool:
C:\Python373>cd Scripts

C:\Python373\Scripts>pip install flask
Collecting flask
...
Installing collected packages: itsdangerous, Werkzeug, flask
Successfully installed Werkzeug-0.15.4 flask-1.1.1 itsdangerous-1.1.0
Let's start initializing the first flask application into the server.py file:
from flask import Flask 
app = Flask (__name__)
# create a wrarp of localhost
@app.route('/')
def home():
 return 'Hello world'
# the default name main 
if __name__ == '__main__':
 app.run()
About Routing and Variable Rules.
This can change it into the server.py script like this:
@app.route('/about')
def about():
 return 'The about page'
@app.route('/blog')
def blog():
 return 'This is the blog'
The next step is the variable rule issue:
# creaza a regula variabila ( variable rules) 
# the type of the variable can be set, see int 
# @app.route('/blog/')
@app.route('/blog/')
def blogpost(blog_id):
 return 'This is the post '+str(blog_id)
To run it, just use:
C:\Python373\my_flask>python server.py
 * Serving Flask app "server" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
The full source code can be found at my GitHub account.