Flask学习入门-day01

Flask 入门

关于安装下载等配置文档的信息可以参考:https://dormousehole.readthedocs.io/en/1.1.2/index.html

使用Pycharm可以很快的生成一个Flask项目

首先写一个基础的网页

from flask import Flask

app = Flask(_name_)

@app.route('/',methods = ['GET','POST'):
def function:
    return index.html

if _name_ = '_main_':
    app.run()

#访问localhost:port 可以展示index.html

加入配置文件:
app.config.from_object("python类或路径") 是一个flask.config.Config对象
该对象源码中from_object

for key in dir(obj):
  if key.isupper():
    self[key] = getattr(obj, key)

因此配置文件中的对象字段要大写,from其他类型可以看flask的config源码。

路由

路由方式:
@app.route 相当于调用了一个 app.add_url_rule
因此添加路由有两个方式:

@app.route('/',methods = ['GET','POST'):
def function:
    return index.html

app.add_url_rule('/',view_fun = funcion)

路由之反向生成url:
在route参数中加入endpoint='n1' 用于生成别名,使用url_for方法调用。

自定义路由转换器: 用于获取/后的输入内容来进行处理。一般用于正则匹配,当匹配成果后都跳转至该页面。
支持str,int,float,path也能够自定义。

@app.route('/index/<int:nid>')
def index(nid):
  print(nid)

# 访问index/111 nid = 111

# 自定义
app.url_map.converters['xxx'] = RegexConverter
class RegexConverter(BaseConverter):
  def __init__(self,map,regex):
    super(RegexConverter, self).__init__(map)
    self.regex = regex
  def to_python(self, value): # 获取到匹配后的参数后如何处理
    return value
  def to_url(self, value): #url_for(**value)中value如何转化,默认直接使用
    val = super(RegexConverter, self).to_url(value)
    return val

新老功能交替:使用重定向
参数redirect_to

@app.route('/index',redirect_to='/new')
@app.route('/new')

视图

请求和相应

requestrender_template

模板

def index():
  context = {

}

  return render_template('index.html',**context)

# 这样在index.html 中可以用{{}} 调用context中的对象
Markup 能够防止xss攻击

@app.template_global()
def function # 在所有模板中定义方法
posted @   Ars丶  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示