当前位置:网站首页>flask-基础代码
flask-基础代码
2022-04-22 00:55:00 【NLstudy33】
# 1.从flask包/模块 中引入flask类
from flask import Flask,current_app,g,request,session,make_response
from flask import render_template,redirect,abort
app = Flask(__name__)
app.debug = True
# current_app当前应用的实例
# g 处理请求时的临时存储对象,每次请求都会重设这个变量
@app.route('/index')
def index():
print('app:',app)
print('current_app',current_app) # current_app当前应用的实例
print(app == current_app) # True 只是值相等,因为我们目前只有一个app启动,没有多个
print(app is current_app) # False 引用是不一样的
return 'index'
@app.route('/')
def helloworld():
# 视图函数
# return 'hello world,susede'
# 访问'/'时,重定向到'/test'页面
# return redirect('/test')
# abort(403) # 触发一个异常,不需要return,会调用后续的forbidden函数
# ip 拦截
ip_list = ['127.0.0.2']
ip = request.remote_addr
if ip in ip_list:
abort(403) # 会调用后续的forbidden函数
return 'hello,sucess,welcome'
# 路由配置使用装饰器 @app.route(url,methods)
@app.route('/test')
def hellotest():
# 视图函数
return 'hello world,test0222,测试函数'
# URL获取视图中的参数page
@app.route('/user/')
@app.route('/user/<page>')
def list_user(page=1):
return '你好,我是第{}页用户'.format(page)
# 使用API配置 app.add_url_rule(url,url_name,view_name)
app.add_url_rule('/test-apimethod','apimethod',hellotest)
# 查看url路由规则
print(app.url_map)
@app.route('/test/req')
def test_request():
'''请求报文练习'''
get_args = request.args
print('get_args',get_args)# get请求参数获取
print(get_args.get('page',1)) # 请求中没有传入page值,那么可以设置默认值
print(request.args.get('name'))
# 获取服务器所在的主机IP地址
headers = request.headers
print(headers)
print('host',headers.get('host'))
# 获取请求用户的ip地址
user_ip = request.remote_addr
print('user_ip',user_ip)
print(request.remote_user)
# 获取user-agent,可以用于爬虫
user_agent = request.headers.get('user-agent',None)
print('User-Agent:','\n',user_agent)
return 'request success'
@app.before_first_request
def first_request():
"""服务器启动后第一个请求到达前"""
print('服务器启动后第一个请求到达前,first_request')
@app.before_request
def per_request():
"""每一个请求到达前"""
print('每一个请求到达前,per_request')
# @app.after_request
# def after_request(reponse):
# """请求结束后执行,过程中产生异常则不执行"""
# print('请求结束后执行,过程中产生异常则不执行,after_request')
# print(reponse.get_json())
# return 'after_request'
@app.route('/test/resp')
def test_response():
"""测试响应"""
return '响应测试,reponse success',405,{
'user_name':'mark','user_id':'mark_id2'}
@app.route('/test/mkresp')
def test_mkresponse():
'''使用make_response构造响应对象'''
mkresp = make_response('这是一个响应对象',403,{
'token':'abc123'
})
mkresp.headers['user_name'] = 'nick_li'
mkresp.status_code = 200
return mkresp
@app.route('/test/htmlresp')
def test_html_response():
'''响应html'''
html = '<html><body><h1 style="color:red">这是一个HTML响应测试</h1></body></html>'
resp = make_response(html)
return resp
@app.route('/test/html')
def test_html():
'''从文件读取html'''
html = render_template('test1.html')
resp = make_response(html,400) # 都可以参考前面的使用
return resp
@app.errorhandler(403)
def forbidden_page(err):
"""403错误提示:你没有权限访问页面"""
print(err)
return '你没有权限访问页面,请联系管理员开通权限'
# if __name__ == '__main__':
# app.run()
版权声明
本文为[NLstudy33]所创,转载请带上原文链接,感谢
https://blog.csdn.net/NLstudy33/article/details/124277248
边栏推荐
- 使用多个可选过滤器过滤 Eloquent 模型
- 腾讯团队实力打造flutter入门教程,1-3年Android开发工程师面试经验分享
- Boutique: thousand word long text teaches you to use byte beating volcanic engine imagex
- Tencent byte and other big companies interview real questions summary, Android programmers how to gracefully cross the 30K barrier
- Even if the times change, it still stands. How powerful is the new Santana product?
- Introduction to Haskell monoid
- SQL Server 2008 uses over (partition by.. order by..) Syntax error displayed
- How can zhiting connect Huawei smart speakers?
- 腾讯T3团队整理,被逼无奈开始狂啃底层技术
- . net core enterprise wechat web page authorization login
猜你喜欢

Boutique: thousand word long text teaches you to use byte beating volcanic engine imagex

Solve the problem that the idea web project does not have small blue dots

DPI released the latest progress report on AI drug research and development

在setTimeout里设置倒数5秒计时的方法

Eventbridge integrated cloud service practice

Huawei cloud hosting experience: your software storage expert

腾讯安卓开发面试经验,HR的话扎心了

Tencent T3 team sorted out and was forced to start gnawing at the underlying technology

物聯網專業未來沒有前途了嗎?

Addition, deletion, modification and query of advanced MySQL data (DML)
随机推荐
腾讯字节等大厂面试真题汇总,Android程序员怎么优雅迈过30K 这道坎
It is recommended to provide outline - one click expansion function
Kotlin - 高阶函数介绍
如果在安装 32 位 Oracle 客户端组件的情况下以 64 位模式运行,将出现此问题
为什么PR导出来的视频,偏紫色?
Akismet plugin tutorial WordPress prevent spam filtering plugin
Ivorysql unveiled at postgresconf SV 2022 Silicon Valley Postgres Conference
Signal and system 2022 spring operation - the ninth operation
Pytorch安装及GroupSpatialSoftmax报错解决
Use of Prometheus
不能再简单的意向锁
Tencent T3 team sorted out and was forced to start gnawing at the underlying technology
物聯網專業未來沒有前途了嗎?
Five tips for novices to do cross-border e-commerce in 2022
Addition, deletion, modification and query of advanced MySQL data (DML)
China venture capital, winter is coming
Fast r-cnn code detailed annotation data shape
JS find array subscript
Logstash import movie lens test data
腾讯T3大牛手把手教你,90%的人看完都说好