analitics

Pages

Wednesday, August 7, 2019

Python 3.7.3 : Using the flask - part 011.

The tutorial for today is focused on the email issue.
I will start with the new python module for flask named flask_mail.
Let's install it:
C:\Python373>cd Scripts

C:\Python373\Scripts>pip3 install flask_mail
Collecting flask_mail
...
Installing collected packages: blinker, flask-mail
Successfully installed blinker-1.4 flask-mail-0.9.1
The next source code let show you how can use this python module.
from flask import Flask 
from flask_mail import Mail, Message

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['TESTING'] = False
app.config['MAIL_SERVER'] = 'smtp...'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = False
#app.config['MAIL_DEBUG'] = True # debug 
app.config['MAIL_USERNAME'] = None
app.config['MAIL_PASSWORD'] = None
# this will send with the name of another@mail.com
#app.config['MAIL_DEFALT_SENDER'] = ('Another mail', 'another@mail.com')
app.config['MAIL_DEFALT_SENDER'] = None
app.config['MAIL_MAX_EMAILS'] = None # limit the messages send
#app.config['MAIL_SUPRESS_SEND'] = False # testing
app.config['MAIL_ASCII_ATTACHMENTS'] = False

# send an email with the flask application
mail = Mail(app)

@app.route('/mail')
def mail():
    #msg = Message('Hey', sender='another@mail.com')
    #msg = Message('Hey', recipients=['catafest@yahoo.com', 'another@mail.com'])
    #msg.add_recipient = ('another@mail.com')
    msg = Message('Hey', recipients=['catafest@yahoo.com'])

    # you can use body or HTML, using both wills receive the HTML first
    #msg.body = 'This is a body text message!'
    msg.html = 'This is a body text message with HTML5 tags!'

    #add a file attachment to message 
    with app.open_resource('photo.jpg') as add_file_res:
         msg.attach('photo.jpg', 'image/jpeg', add_file_res.read())
    '''
    #create a template message 
    msg = Message(
    subject ='',
    recipients=[],
    body = '',
    html = '',
    sender = '',
    cc = [],
    bcc = [],
    attachments = [],
    reply_to = [],
    date = '',
    charset = [],
    extra_headers = {'':''},
    mail_options = [],
    rcpt_options = []
    )
    '''
    #send mail
    mail.send(msg)
    return 'Message sent!'

@app.route('/bulk')
def bulk():
    users = [{'name':'Me', 'email':'another@mail.com'}]
    # open an connection 
    with mail.connect() as con:
         for user in users:
             msg = Message('Bulk message!', recipients=[user['email']]
             msg.body = 'Body message!'
             con.send(msg)
'''
# another example 
@app.route('/bulk')
def bulk():
    users = [{'name':'Me', 'email':'another@mail.com'}]
    # open an connection 
    with mail.connect() as con:
         for user in users:
             msg = Message('Bulk message!', recipients=[user.email]
             msg.body = 'Body message!'
             con.send(msg)
'''
if __name__ == '__main__':
    app.run()
You can see you need to set the settings for your mail server and then use it into flaks application.
The source code is easy to understand if you follow the commented rows.
I add also put into comments alternative examples for the template message and the bulk function.
This is the first step into sending emails with flask.
We can have a complete implementation on the project but all depends on project structure.

Tuesday, August 6, 2019

Python 3.7.3 : Using the flask - part 010.

If you read my last tutorial about flask then you understand how to use the structure flask project with views.py and models.py.
If you run it and open the browser with http://127.0.0.1:5000/texts/ the result will be this:
{"texts":[{"title":"first title","txt_content":"this is first content"},{"title":null,"txt_content":null}]}
Let's create a file .env into the base folder named my_flask and add this source code:
SECRET_KEY='secret key'
DEBUG=True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = sqlite:///texts.sqlite
Let's create a settings.py file into blue_test folder to get these settings:
import os
from os import environ
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI')
My blue_test project comes with the old views.py and a new routes.py file with this source code:
from flask import Blueprint, jsonify, request

api = Blueprint('api', __name__)

@api.route('/')
def home():
    return jsonify({'result' : 'You are in main page!'}) 
I create an extensions.py python script to deal with the database, see the source code:
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
With this new python file will solve the avoid circular importing of circular dependency of importing db.
This changes can be made on models.py and views.py, like this:
# import db from base folder, see dot
from .extensions import db 
This two files views.py and routes.py come with two Blueprint's: main and api.
Into the __init__.py will need to import and register both :
from .extensions import db
from .models import Texts
from .routes import api
from .views import main
...
    app.register_blueprint(main)
    app.register_blueprint(api)
If you run it into my_flask folder with:
C:\Python373\my_flask>set FLASK_APP=blue_test

C:\Python373\my_flask>flask run
 * Serving Flask app "blue_test"
 * Environment: production
...
The result into the browser area with http://127.0.0.1:5000/ for the routes.py blueprint api will be:
{"result":"You are in main page!"}
The result into the browser area with http://127.0.0.1:5000/texts/ for the views.py blueprint main will be:
{"texts":[{"title":"first title","txt_content":"this is first content"},{"title":null,"txt_content":null}]}
This shows you how to link multiple blueprints into one project.
You can see the full project at my GitHub project.

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.