Python Flask Web 框架入门

一、最基本结构

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run(debug=True)

二、orm模型 

#encoding:utf-8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import or_,and_
app=Flask(__name__)
# 数据库配置
USERNAME = 'root'
PASSWORD = '123456'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'xl_flask'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME,PASSWORD,HOST,PORT,DATABASE)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # 动态跟踪修改设置,如果未设置会弹出警告
app.config['SQLALCHEMY_ECHO'] = True # 查询时会显示原始的sql语句
db = SQLAlchemy(app) # 创建实例

class Article(db.Model):
    __tablename__='article'
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    title=db.Column(db.String(200),nullable=False)
    content=db.Column(db.Text,nullable=False)
# 创建表
@app.route('/createtable')
def create_table():
    db.create_all()
    return "创建表成功"

# 添加表
@app.route('/add')
def article_view():
    article=Article(title="钢条",content="xxx")#添加数据
    article1=Article(title="华华",content="yyy")
    db.session.add(article)
    db.session.add(article1)
    db.session.commit()
    return "添加成功"

# 删除表
@app.route('/droptable')
def droptable():
    db.drop_all()
    return '删除表成功'

# 查询表
@app.route('/search')
def search():
    results=Article.query.all()
    print(results)
    rs=Article.query.filter(Article.id==1).first()
    print(rs)
    rs1 = Article.query.filter_by(id=1).first()
    print(rs1)
    rs2 = Article.query.filter(Article.content.like("%x%")).first()
    print(rs2)
    rs3= Article.query.filter(Article.content.like("%x%"))
    print(rs3)
    # # and
    rs4=Article.query.filter(Article.id==1,Article.content.like('%x%')).first()
    print(rs4)
    rs5 = Article.query.filter( Article.content.like('%x%')).filter(Article.id==1).first()
    print(rs5)
    # # or
    rs6=Article.query.filter(or_(Article.id==2,Article.content.like('%x%'))).first()
    print(rs6)
    return '查询成功'

# 修改表
@app.route('/update')
def update():
    c=Article.query.filter(Article.id==1).first()
    c.content='C200'
    db.session.commit()
    return '修改成功'

# 删除表项
@app.route('/delete')
def delete():
    c=Article.query.filter(Article.id==1).first()
    db.session.delete(c)
    db.session.commit()
    return '删除成功'



@app.route('/')
def hello_world():
    engine=db.get_engine()
    with engine.connect() as conn:
        result=conn.execute('select 1')
        print(result.fetchone())
    return 'Hello World!'


if __name__ == '__main__':
    app.run(debug=True)

 最后给亲爱的小伙伴分享一下Flask学习必备资料,点击下面链接可取: 

欢迎来到 Flask 的世界 — Flask中文文档(2.1.x)

宝宝们,喜欢的点赞支持一下,谢谢宝宝们啦!

你可能感兴趣的:(Flask,flask,python,后端)