flask 项目
from flask import Flask,request
app=Flask(__name__)
@app.route('/')
def index():
print(request.path)
return 'hello world'
if __name__ == '__main__':
app.run()
2 登录,显示用户信息-小案例
from flask import Flask,render_template,request,redirect,session,url_for
app = Flask(__name__)
app.debug = True
app.secret_key = 'sdfsdfsdfsdf'
USERS = {
1:{'name':'张三','age':18,'gender':'男','text':"道路千万条"},
2:{'name':'李四','age':28,'gender':'男','text':"安全第一条"},
3:{'name':'王五','age':18,'gender':'女','text':"行车不规范"},
}
@app.route('/detail/<int:nid>',methods=['GET'])
def detail(nid):
user = session.get('user_info')
if not user:
return redirect('/login')
info = USERS.get(nid)
return render_template('detail.html',info=info)
@app.route('/index',methods=['GET'])
def index():
user = session.get('user_info')
if not user:
url = url_for('l1')
return redirect(url)
return render_template('index.html',user_dict=USERS)
@app.route('/login',methods=['GET','POST'],endpoint='l1')
def login():
if request.method == "GET":
return render_template('login.html')
else:
user = request.form.get('user')
pwd = request.form.get('pwd')
if user == 'cxw' and pwd == '123':
session['user_info'] = user
return redirect('http://www.baidu.com')
return render_template('login.html',error='用户名或密码错误')
if __name__ == '__main__':
app.run()
jinja2 模板语法
{% for k,v in user_dict.items() %}
<tr>
<td>{{k}}</td>
<td>{{v.name}}</td>
<td>{{v['name']}}</td>
<td>{{v.get('name')}}</td>
<td><a href="/detail/{{k}}">查看详细</a></td>{{error}}
</tr>
{% endfor %}
1 模板层 要渲染的字符串|safe
2 后端:Markup('<input type="text">')
三板斧
return 字符串
return render_template('detail.html',info=info)
return redirect('/login')
获取前端请求携带的数据
request.query_string
request.form.get('user')
session.get('user_info')
session['user_info'] = user
路由
路由写法(路径,支持的请求方式,别名)
@app.route('/login',methods=['GET','POST'],endpoint='l1')
分组(django中的有名分组)
@app.route('/detail/<int:nid>',methods=['GET'])
反向解析
url_for('别名')
url = url_for('l1')
return redirect(url)
配置文件
通过SECRET_KEY加密以后,当做cookie返回给浏览器
下次发送请求,携带cookie过来,反解,再放到session中
方式一
app.config['DEBUG'] = True
PS: 由于Config对象本质上是字典,所以还可以使用
app.config.update(...)
方式二
app.config.from_pyfile("python文件名称")
如:
settings.py
DEBUG = True
方式三
app.config.from_object('settings.TestingConfig')
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = 'sqlite://:memory:'
class ProductionConfig(Config):
DATABASE_URI = 'mysql://user@localhost/foo'
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
转换器
DEFAULT_CONVERTERS = {
'default': UnicodeConverter,
'string': UnicodeConverter,
'any': AnyConverter,
'path': PathConverter,
'int': IntegerConverter,
'float': FloatConverter,
'uuid': UUIDConverter,
}
路由的本质
1 本质就是:app.add_url_rule()
2 endpoint:如果不写默认是函数名,endpoint不能重名
app.add_url_rule参数
@app.route和app.add_url_rule参数:
rule, URL规则
view_func, 视图函数名称
defaults = None, 默认值, 当URL中无参数,defaults = {'k': 'v'} 为函数提供固定参数
endpoint = None, 名称,用于反向生成URL,即: url_for('名称')
methods = None, 允许的请求方式,如:["GET", "POST"]
strict_slashes = None
'''
@app.route('/index', strict_slashes=False)
#访问http://www.xx.com/index/ 或http://www.xx.com/index均可
@app.route('/index', strict_slashes=True)
#仅访问http://www.xx.com/index
'''
redirect_to = None,
'''
@app.route('/index/<int:nid>', redirect_to='/home/<nid>')
'''
CBV
from flask import Flask,request,render_template,redirect
from flask import views
app=Flask(__name__)
class IndexView(views.View):
methods = ['GET']
decorators = [auth, ]
def dispatch_request(self):
return 'Index!'
def auth(func):
def inner(*args, **kwargs):
print('before')
result = func(*args, **kwargs)
print('after')
return result
return inner
class IndexView(views.MethodView):
methods = ['GET']
decorators = [auth, ]
def get(self):
return "我是get请求"
def post(self):
return '我是post请求'
app.add_url_rule('/index',view_func=IndexView.as_view('index'))
if __name__ == '__main__':
app.run()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现