唤醒手腕 Python - Flask 框架详细学习笔记(英文版)

What is Flask?

official website: https://flask.palletsprojects.com

Welcome to Flask’s documentation. Get started with Installation and then get an overview with the Quickstart. There is also a more detailed Tutorial that shows how to create a small but complete application with Flask.

Common patterns are described in the Patterns for Flask section. The rest of the docs describe each component of Flask in detail, with a full reference in the API section.

app.run()

if __name__ == '__main__':
    app.run(debug=True)
    # default port of Flask is 5000
    # ssl_context=('crt','key') : launch SSL Service

"""
    debug mode : the server will restart when codes updated
    return information of error in browser.
"""

addtional options: --host=0.0.0.0 --port=8080

Click the Edit Configurations in the top-right corner of the screen, to set some properties of Running.

在这里插入图片描述

request.args

@app.route('/list/show')
def show_page_data():
    """
        :argument   type is dict class
    :return: params of request's URL
    """
    page = request.args.get("page", type=int, default=100)
    return f"page is {
      
      page}"

When appointed argument isn’t existed, the value of argument is produced default value.

when client visit, response the content of show_page_data function.

Information such as status codes can be processed either automatically by Flask or formulated by programming.

render_template

create User class in app.py

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

create mapping of view, as following

@app.route('/html')
def show_html():
    user = User(name='wrist', age=20)
    return render_template('index.html', name='wristwaking', user=user)

create index.html in src templates/index.html

<div> name is : {
   
   { name }} </div>
<div> {
   
   { user.name }} {
   
   { user.age }} </div>

connect MySQL

approachs of connecting mysql dabtabase between flask-server

MySQL-python: made of C language process best

mysqlclient : One of items of MySQL-python

pymysql: made of Python totally, shortcomings: Low efficiency

mysql-connector-python: made of Python totally, shortcomings: Low efficiency

SQLAlchemy introduction

official website: https://www.sqlalchemy.org/

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

It provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

在这里插入图片描述
Install via pip

When pip is available, the distribution can be downloaded from PyPI and installed in one step:

pip install SQLAlchemy

Checking the Installed SQLAlchemy Version

This documentation covers SQLAlchemy version 2.0. If you’re working on a system that already has SQLAlchemy installed, check the version from your Python prompt like this:


>>> import sqlalchemy
>>> sqlalchemy.__version__  
2.0.0

Flask ERROR Example

ModuleNotFoundError: No module named ‘pymysql’

python3 : default connecting-driver is pymysql

python2 : default connecting-driver is pymysql or MySQLdb

sqlalchemy : default connecting-driver is MySQLdb

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql

pymysql.install_as_MySQLdb()
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]:3306/flask?charset:utf-8'
app.config['SQLALCHEMY_ECHO'] = True


class DFG(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.

with app.app_context():
    with db.engine.connect() as conn:
        rs = conn.execute("select 1")
        print(rs.fetchone())

ORM

Object Relational Mapping, be omitted.

class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(100), nullable=False)

with app.app_context():
    db.create_all()

Create view function to add data through access to MySQL.

@app.route('/add')
def add_user():
    user = User(username='wrist', password='waking')
    db.session.add(user)
    db.session.commit()
    return "success"

The data of MySQL user Table, as following
在这里插入图片描述
How to find data by ORM

@app.route('/find')
def find_user():
    user = User.query.get(1)
    print(user.username)  # wrist
    return "find successfully"

flask-migrate

download method: pip install flask-migrate

在这里插入图片描述

Three steps of the mapping of the ORM model into a table

Terminal >> flask db init # just once time

Identify the ORM model changes and generate the migration scripts

Terminal >> flask db migrate

Run the migration script and synchronize it to the database

Terminal >> flask db upgrade

猜你喜欢

转载自blog.csdn.net/qq_47452807/article/details/129018643
今日推荐