Flask的简单使用

Flask的简单使用

1、Flask简介

Flask是一款由Python编写的轻量级Web框架,其内核简单轻便且易扩展,使用起来十分方便。Flask也被称之为“微框架(microframework)”。

2、Flask基本使用

2.1、安装Flask

pip install Flask

2.2、创建app和路由

新建app.py

from flask import Flask

app = Flask(__name__)


@app.route(rule="/hello")
def hello():
    result = {"code": 200,
              "msg": "hello",
              "data": None}
    return result


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8888, debug=True)

如此便创建出了一个名为app的应用且有一个名为hello的接口,运行在本机8888端口上。

2.3.1 普通GET传参

from flask import Flask
from flask import request

app = Flask(__name__)


@app.route(rule="/hello1")
def hello1():
    name = request.args.get("name")
    return "hello " + name


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8888, debug=True)

2.3.2 Restful get传参

from flask import Flask
from flask import request

app = Flask(__name__)


@app.route(rule="/hello2/<string:name>")
def hello2(name):
    return "hello " + name


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8888, debug=True)

2.4.1 post form传参

from flask import Flask
from flask import request

app = Flask(__name__)


@app.route(rule="/hello3", methods=["POST"])
def hello3():
    name = request.form.get("name")
    return "hello " + name


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8888, debug=True)

2.4.2 post json传参

from flask import Flask
from flask import request

app = Flask(__name__)


@app.route(rule="/hello4", methods=["POST"])
def hello4():
    json = request.get_json()
    name = json["name"]
    return "hello " + name


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8888, debug=True)

3、Flask扩展

3.1、blueprints(蓝图)

Flask使用蓝图来实现跨模块甚至跨应用间组建的协同合作,蓝图提供了Flask扩展应用的核心方法。蓝图和Flask应用对象十分相似,但是蓝图并不是一个Flask的应用对象。

3.1.1、 创建一个蓝图

新建一个firstBluePrint.py

from flask import Blueprint


firstBluePoint = Blueprint("firstBluePoint", __name__, url_prefix="/first")


@firstBluePoint.route(rule="/hello5")
def hello5():
    return "hello BluePoint"

3.1.2、 注册蓝图

在app.py中注册这个蓝图

from flask import Flask
from flask import request
from firstBluePrint import firstBluePoint

app = Flask(__name__)
app.register_blueprint(firstBluePoint)


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8888, debug=True)

3.2、SQLAlchemy

SQLAlchemy是Python工具库中十分强大的ORM(Object Relationship Mapping 对象关系映射)框架,通过使用SQLAlchemy,程序员可以无需编写繁长的SQL语句,直接通过对象来操作数据库。但是用ORM也有其对应的缺点:效率低,复杂查询的语法复杂。
SQLALchemy也可以直接使用原生SQL语句。

3.2.1、下载flask-sqlalchemy

pip install flask-sqlalchemy

3.2.2、初始化

建表
在这里插入图片描述
建立model、db和路由

from flask import Flask
from flask import request
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)


app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:root@127.0.0.1:3306/weekshareflask"
app.config["SQLALCHEMY_ECHO"] = True
db = SQLAlchemy(app)


class Student(db.Model):
    __tablename__ = "student"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    age = db.Column(db.Integer, nullable=False)

    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def to_json(self):
        return {"id": self.id,
                "name": self.name,
                "age": self.age}


@app.route(rule="/createStudent")
def createStudent():
    name = request.args.get("name")
    age = request.args.get("age")
    student = Student(name, age)
    db.session.add(student)
    db.session.commit()
    return "ok"

@app.route(rule="/getStudent/<int:id>")
def getStudent(id):
    student = Student.query.filter_by(id=id).one().to_json()
    return student

@app.route(rule="/getStudents/<int:age>")
def getStudents(age):
    students = Student.query.filter_by(age=age).all()
    return [student.to_json() for student in students]


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8888, debug=True)

4、Flask代码风格

如果将所有的配置和路由都写在同一个文件中,那么这个文件不可避免的将会臃肿无比,此时我们就需要对这些代码进行拆分,将不同功能的代码放入适合他的包里。

4.1、总体项目结构

在这里插入图片描述
App:项目总包
App.__init__.py

from flask import Flask
from App.extension import init_ext
import App.config
from App.views import init_blue


def create_app():
    app = Flask(__name__)
    app.config.from_object(config)
    init_ext(app=app)
    init_blue(app=app)
    return app

App.model:存放模型类
App.model.student.py

from App.extension import db


class Student(db.Model):
    __tablename__ = "student"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    age = db.Column(db.Integer, nullable=False)

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

    def to_json(self):
        return {"id": self.id,
                "name": self.name,
                "age": self.age}

App.student.__init__.py

from .student import Student

App.views:存放视图类
App.views.hello.py

from flask import Blueprint, request

hello_blue = Blueprint("hello_blue", __name__)


@hello_blue.route(rule="/hello")
def hello():
    result = {"code": 200,
              "msg": "hello",
              "data": None}
    return result


@hello_blue.route(rule="/hello1")
def hello1():
    name = request.args.get("name")
    return "hello " + name


@hello_blue.route(rule="/hello2/<string:name>")
def hello2(name):
    return "hello " + name


@hello_blue.route(rule="/hello3", methods=["POST"])
def hello3():
    name = request.form.get("name")
    return "hello " + name


@hello_blue.route(rule="/hello4", methods=["POST"])
def hello4():
    json = request.get_json()
    name = json["name"]
    return "hello " + name

App.views.first_blueprint.py

from flask import Blueprint

first_blue = Blueprint("first_blue", __name__, url_prefix="/first")


@first_blue.route(rule="/hello5")
def hello5():
    return "hello BluePoint"

App.views.student.py

from flask import Blueprint, request

from App.extension import db
from App.models import Student

student_blue = Blueprint("student_blue", __name__)


@student_blue.route(rule="/createStudent")
def createStudent():
    name = request.args.get("name")
    age = request.args.get("age")
    student = Student(name, age)
    db.session.add(student)
    db.session.commit()
    return "ok"


@student_blue.route(rule="/getStudent/<int:id>")
def getStudent(id):
    student = Student.query.filter_by(id=id).one().to_json()
    return student


@student_blue.route(rule="/getStudents/<int:age>")
def getStudents(age):
    students = Student.query.filter_by(age=age).all()
    return [student.to_json() for student in students]

App.__init__.py

from .first_blueprint import first_blue
from .hello import hello_blue
from .student import student_blue


def init_blue(app):
    app.register_blueprint(first_blue)
    app.register_blueprint(hello_blue)
    app.register_blueprint(student_blue)

config:存放app配置
App.config.py

SQLALCHEMY_DATABASE_URI = "mysql://root:root@127.0.0.1:3306/weekshareflask"
SQLALCHEMY_ECHO = True

extension:初始化拓展组件
App.extension.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


def init_ext(app):
    db.init_app(app=app)

manage:项目启动类
App.manage.py

from App import create_app

app = create_app()

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8888, debug=True)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值