ORM映射和路由系统
ORM映射:
OBJECT ====> 对象
RELATION ===> 联系
MODEL ===> 数据模型
安装pyMysql
安装flask-sqlAchemy
导入:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
#因为sqlAlchemy模块默认是采用mysqldb模块进行数据库连接,python3数据库连接mysqldb不支持,
import pymysql
pymysql.install_as_MySQLdb()
# python3需要加上以上2句语句
import config
设置配置文件:
HOSTNAME = '127.0.0.1'#主机名
PORT = 3306#端口号
DATABASE = 'cms'#数据库名称
USERNAME = 'root'#用户名
PASSWORD = '123456'#密码
#数据库SQLAlchemy,SQLALCHEMY_DATABASE_URI
DB_URI = 'mysql+mysqldb://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = False
路由系统:
1.可传入参数:
@app.route('/user/<username>') #常用的 不加参数的时候默认是字符串形式的
@app.route('/post/<int:post_id>') #常用的 #指定int,说明是整型的
@app.route('/post/<float:post_id>')
@app.route('/post/<path:path>')
@app.route('/login', methods=['GET', 'POST'])
|
1
2
3
4
5
6
7
8
9
|
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter,} |
2.反向生成URL: url_for
endpoint("name") #别名,相当于django中的name
from flask import Flask, url_for
@app.route('/index',endpoint="xxx") #endpoint是别名
def index():
v = url_for("xxx")
print(v)
return "index"
@app.route('/zzz/<int:nid>',endpoint="aaa") #endpoint是别名
def zzz(nid):
v = url_for("aaa",nid=nid)
print(v)
return "index2"


浙公网安备 33010602011771号