Flask基础-配置,路由
一,配置文件
flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为:
{
'DEBUG': get_debug_flag(default=False), 是否开启Debug模式
'TESTING': False, 是否开启测试模式
'PROPAGATE_EXCEPTIONS': None,
'PRESERVE_CONTEXT_ON_EXCEPTION': None,
'SECRET_KEY': None,
'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
'USE_X_SENDFILE': False,
'LOGGER_NAME': None,
'LOGGER_HANDLER_POLICY': 'always',
'SERVER_NAME': None,
'APPLICATION_ROOT': None,
'SESSION_COOKIE_NAME': 'session',
'SESSION_COOKIE_DOMAIN': None,
'SESSION_COOKIE_PATH': None,
'SESSION_COOKIE_HTTPONLY': True,
'SESSION_COOKIE_SECURE': False,
'SESSION_REFRESH_EACH_REQUEST': True,
'MAX_CONTENT_LENGTH': None,
'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
'TRAP_BAD_REQUEST_ERRORS': False,
'TRAP_HTTP_EXCEPTIONS': False,
'EXPLAIN_TEMPLATE_LOADING': False,
'PREFERRED_URL_SCHEME': 'http',
'JSON_AS_ASCII': True,
'JSON_SORT_KEYS': True,
'JSONIFY_PRETTYPRINT_REGULAR': True,
'JSONIFY_MIMETYPE': 'application/json',
'TEMPLATES_AUTO_RELOAD': None,
}
方式一:
app.config['DEBUG'] = True PS: 由于Config对象本质上是字典,所以还可以使用app.config.update(...) 方式二:
app.config.from_pyfile("python文件名称")
如:
settings.py
DEBUG = True app.config.from_pyfile("settings.py") app.config.from_envvar("环境变量名称")
环境变量的值为python文件名称名称,内部调用from_pyfile方法 app.config.from_json("json文件名称")
JSON文件名称,必须是json格式,因为内部会执行json.loads app.config.from_mapping({'DEBUG':True})
字典格式 app.config.from_object("python类或类的路径") app.config.from_object('pro_flask.settings.TestingConfig') settings.py 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 PS: 从sys.path中已经存在路径开始写 PS: settings.py文件默认路径要放在程序root_path目录,如果instance_relative_config为True,则就是instance_path目录
案例1
from flask import Flask app = Flask(__name__)
app.config.from_object("settings.DevelopmentConfig")
@app.route('/')
def hello_world():
return 'Hello World!' if __name__ == '__main__':
app.run()
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = 'sqlite://:memory:' class ProductionConfig(Config):
DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config):
DEBUG = False class TestingConfig(Config):
TESTING = True
2. URL 反向解析
from flask import Flask,url_for app = Flask(__name__)
app.config.from_object("settings.DevelopmentConfig")
# @app.route('/')
# def hello_world():
# return 'Hello World!' # 1. index函数路由
@app.route("/index",endpoint="n1") #<string:xx><default:xx> <xxx> 都表示字符串
def index():
print(id)
return "hello" #2. order 函数路由
@app.route("/order",endpoint="n2")
def order():
print("order")
return "hello" #3. user 函数路由
@app.route("/user")
def user():
print(url_for("n1")) #打印结果 /index
print(url_for("n2")) #打印结果 /order
#endport ,为url起别名,根据别名可以反向生成url
return 'hello11' if __name__ == '__main__':
app.run()
3.路由系统
三、路由系统
@app.route('/user/<username>')
@app.route('/post/<int:post_id>')
@app.route('/post/<float:post_id>')
@app.route('/post/<path:path>')
@app.route('/login', methods=['GET', 'POST'])
常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:
DEFAULT_CONVERTERS = {
'default': UnicodeConverter,
'string': UnicodeConverter,
'any': AnyConverter,
'path': PathConverter,
'int': IntegerConverter,
'float': FloatConverter,
'uuid': UUIDConverter,
}
def auth(func):
def inner(*args, **kwargs):
print('before')
result = func(*args, **kwargs)
print('after')
return result return inner @app.route('/index.html',methods=['GET','POST'],endpoint='index')
@auth
def index():
return 'Index' 或 def index():
return "Index" self.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
or
app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
app.view_functions['index'] = index 或
def auth(func):
def inner(*args, **kwargs):
print('before')
result = func(*args, **kwargs)
print('after')
return result return inner class IndexView(views.View):
methods = ['GET']
decorators = [auth, ] def dispatch_request(self):
print('Index')
return 'Index!' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint 或 class IndexView(views.MethodView):
methods = ['GET']
decorators = [auth, ] def get(self):
return 'Index.GET' def post(self):
return 'Index.POST' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint @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, 对URL最后的 / 符号是否严格要求,
如:
@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>')
或
def func(adapter, nid):
return "/home/888"
@app.route('/index/<int:nid>', redirect_to=func)
subdomain=None, 子域名访问
from flask import Flask, views, url_for app = Flask(import_name=__name__)
app.config['SERVER_NAME'] = 'wupeiqi.com:5000' @app.route("/", subdomain="admin")
def static_index():
"""Flask supports static subdomains
This is available at static.your-domain.tld"""
return "static.your-domain.tld" @app.route("/dynamic", subdomain="<username>")
def username_index(username):
"""Dynamic subdomains are also supported
Try going to user1.your-domain.tld/dynamic"""
return username + ".your-domain.tld" if __name__ == '__main__':
app.run()
注册路由原理
4 .文件上传
@app.route("/upload",methods=["GET","POST"])
def upload():
if request.method =="GET":
return render_template("upload.html")
from werkzeug.datastructures import FileStorage
file =request.files.get("ff")
print("file是什么:",file,"file类型:",type(file))
print("file_name:",file.filename)
print("file_stream:",file.stream)
#方法一、
file_path =os.path.join('upload',file.filename)
print(file_path)
with open(file_path,"wb") as f:
file.save(f)
#方法二、
file.save(file_path) 直接保存文件路径.
return "上传成功"
if __name__ == '__main__':
app.run()
输出结果:


html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>upload</title>
</head>
<body> <form method="post" enctype="multipart/form-data"> <input type="file" name="ff"> <input type="submit" value="提交"> </form> </body>
</html>
5、 请求和相应.
复制代码
from flask import Flask
from flask import request
from flask import render_template
from flask import redirect
from flask import make_response app = Flask(__name__) @app.route('/login.html', methods=['GET', "POST"])
def login(): # 请求相关信息
# request.method
# request.args
# request.form
# request.values
# request.cookies
# request.headers
# request.path
# request.full_path
# request.script_root
# request.url
# request.base_url
# request.url_root
# request.host_url
# request.host
# request.files
# obj = request.files['the_file_name']
# obj.save('/var/www/uploads/' + secure_filename(f.filename)) # 响应相关信息
# return "字符串"
# return render_template('html模板路径',**{})
# return redirect('/index.html') # response = make_response(render_template('index.html'))
# response是flask.wrappers.Response类型
# response.delete_cookie('key')
# response.set_cookie('key', 'value')
# response.headers['X-Something'] = 'A value'
# return response return "内容" if __name__ == '__main__':
app.run()
6. flask-session



Flask基础-配置,路由的更多相关文章
- Flask基础(05)-->路由的基本定义
# 导入Flask from flask import Flask # 创建Flask的应用程序 app = Flask(__name__) # http://127.0.0.1:5000/123或者 ...
- Flask(2)- 装饰器的坑及解决办法、flask中的路由/实例化配置/对象配置/蓝图/特殊装饰器(中间件、重定义错误页面)
一.装饰器的坑以及解决方法 1.使用装饰器装饰两个视图函数,代码如下 from flask import Flask, redirect, render_template, request, sess ...
- flask框架--设置配置文件的几种方式 与Flask两种配置路由的方式
设置配置文件的几种方式 ==========方式一:============ app.config['SESSION_COOKIE_NAME'] = 'session_lvning' #这种方式要把所 ...
- koa 基础(二)配置路由
1.配置路由 app.js // 引入模块 const Koa = require('koa'); const Router = require('koa-router'); // 实例化 let a ...
- Cisco基础(二):三层交换vlan间通信、多交换机vlan间通信、三层交换配置路由、RIP动态路由配置、三层交换配置RIP动态路由
一.三层交换vlan间通信 目标: VLAN实现了广播域的隔离,同时也将VLAN间的通信隔离了.三层交换技术使得VLAN间可以通信. 通过三层交换实现VLAN间通信 方案: 为了解决了传统路由器低速. ...
- flask基础之app初始化(四)
前言 flask的核心对象是Flask,它定义了flask框架对于http请求的整个处理逻辑.随着服务器被启动,app被创建并初始化,那么具体的过程是这样的呢? 系列文章 flask基础之安装和使用入 ...
- Flask 基础知识一
Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后 ...
- 笔记-flask基础操作
笔记-flask基础操作 1. 前言 本文为flask基础学习及操作笔记,主要内容为flask基础操作及相关代码. 2. 开发环境配置 2.1. 编译环境准备 安装相关Lib ...
- Flask基础(16)-->WTForms表单创建和简单验证
Flask基础(16)-->WTForms表单创建和简单验证 前言:使用Flask_WTF需要配置参数SECRET_KEYCSRF_ENABLED是为了CSRF(跨站请求伪造)保护.SECRET ...
随机推荐
- MongoDB的数据类型(四)
JSON JSON是一种简单的数据表示方式,它易于理解.易于解析.易于记忆.但从另一方面来说,因为只有null.布尔.数字.字符串.数组和对象这几种数据类型,所以JSON有一定局限性.例如,JSON没 ...
- DataTable学习笔记---排序细则、列隐藏
耽误了好几天,因为要做一个嵌入式的实验-android内核编译与裁剪,很久之前装的wubi不知道为什么运行出错了,然后看着当前的win7系统觉得有点讨厌了,也是因为快1年半没装机了,所以就重新装机了, ...
- linux文件管理2
1.显示文件内容 cat : 显示文件内容 tac : 倒序显示内容 2.更改文件权限 chmod :更改文件权限 -R 递归改变 chown :更改文件拥有者 -R 递归改变 chgrp :更改文件 ...
- Django开发问题及解决方法汇总
1. manage.py@MxOnline > makemigrations users manage.py@MxOnline > migrate users 2. 操作django的ad ...
- python yaml
一.安装PyYAML http://pyyaml.org/ 二.入门参考 http://www.cnblogs.com/c9com/archive/2013/01/05/2845539.html ht ...
- db2 查看表空间使用率
1. 统计所有节点表空间使用率 select substr(TABLESPACE_NAME,1,20) as TBSPC_NAME,bigint(TOTAL_PAGES * PAGE_SIZE)/10 ...
- Stripies
/* Our chemical biologists have invented a new very useful form of life called stripies (in fact, th ...
- 论坛遇到附件上传失败问题总结(discuz)
(1)bbs/source/class/class_upload.php 50行左右,注释$attach['target'] $attach['target'] = DISCUZ_ROOT.'./da ...
- FTP 搭建
FTP 搭建 FTP 是 File Transfer Protocol(文件传输协议)的英文简称,它工作在 0SI 模型的第七层,TCP 模型的第四屋上,即应用层. 一.FTP 简介 FTP 会话时包 ...
- JavaScript的replace方法与正则表达式结合应用讲解
大家好!!今晚在华软G43*宿舍没什么事做,把javascript中replace方法讲解一下,如果讲得不对或不合理是情理之中的事,因为我不是老鸟,也不是菜鸟,我也不知道我当底是什么鸟??呵~~ re ...