Home Backend Development Python Tutorial Python的Flask开发框架简单上手笔记

Python的Flask开发框架简单上手笔记

Jun 10, 2016 pm 03:07 PM
flask python

最简单的hello world

#!/usr/bin/env python
# encoding: utf-8

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
  return 'hello world'

if __name__ == '__main__':
  app.run(debug=True)
  #app.run(host='127.0.0.1', port=8000)

Copy after login

之后,访问http://localhost:5000

支持post/get提交

@app.route('/', methods=['GET', 'POST'])
Copy after login

多个url指向

@app.route('/')
@app.route('/index')
Copy after login

不管post/get使用统一的接收

from flask import request
args = request.args if request.method == 'GET' else request.form
a = args.get('a', 'default')
Copy after login

处理json请求
request的header中

"Content-Type": "application/json"
Copy after login

处理时:

data = request.get_json(silent=False)
Copy after login

获取post提交中的checkbox

{%for page in pages %}
<tr><td><input type=checkbox name=do_delete value="{{ page['id'] }}"></td><td>
{%endfor%}

page_ids = request.form.getlist("do_delete")

Copy after login

使用url中的参数

@app.route('/query/<qid>/')
def query(qid):
  pass
Copy after login

在request开始结束dosomething
一般可以处理数据库连接等等

from flask import g

app = .....

@app.before_request
def before_request():
  g.session = create_session()

@app.teardown_request
def teardown_request(exception):
  g.session.close()

Copy after login

注册Jinja2模板中使用的过滤器

@app.template_filter('reverse')
def reverse_filter(s):
  return s[::-1]
Copy after login

或者

def reverse_filter(s):
  return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter
Copy after login

可以这么用

def a():...
def b():...

FIL = {'a': a, 'b':b}
app.jinja_env.filters.update(FIL)

Copy after login

注册Jinja2模板中使用的全局变量

JINJA2_GLOBALS = {'MEDIA_PREFIX': '/media/'}
app.jinja_env.globals.update(JINJA2_GLOBALS)
Copy after login

定义应用使用的template和static目录

app = Flask(__name__, template_folder=settings.TEMPLATE_FOLDER, static_folder = settings.STATIC_PATH)
Copy after login

使用Blueprint

from flask import Blueprint
bp_test = Blueprint('test', __name__)
#bp_test = Blueprint('test', __name__, url_prefix='/abc')

@bp_test.route('/')

--------
from xxx import bp_test

app = Flask(__name__)
app.register_blueprint(bp_test)

Copy after login

实例:

bp_video = Blueprint('video', __name__, url_prefix='/kw_news/video')
@bp_video.route('/search/category/', methods=['POST', 'GET'])
#注意这种情况下Blueprint中url_prefix不能以 '/' 结尾, 否则404
Copy after login

使用session
包装cookie实现的,没有session id

app.secret_key = 'PS#yio`%_!((f_or(%)))s'

Copy after login

然后

from flask import session

session['somekey'] = 1
session.pop('logged_in', None)

session.clear()

#过期时间,通过cookie实现的
from datetime import timedelta
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)

Copy after login

反向路由

from flask import url_for, render_template

@app.route("/")
def home():
  login_uri = url_for("login", next=url_for("home"))
  return render_template("home.html", **locals())

Copy after login

上传文件

<form action="/image/upload/" method="post" enctype="multipart/form-data">
<input type="file" name="upload" />
Copy after login

接收

f = request.files.get('upload')
img_data = f.read()
Copy after login

直接返回某个文件

return send_file(settings.TEMPLATE_FOLDER + 'tweet/tweet_list.html')
Copy after login

请求重定向

flask.redirect(location, code=302) the redirect status code. defaults to 302.Supported codes are 301, 302, 303, 305, and 307. 300 is not supported.

@app.route('/')
def hello():
  return redirect(url_for('foo'))

@app.route('/foo')
def foo():
  return'Hello Foo!'

Copy after login

获取用户真实ip
从request.headers获取

real_ip = request.headers.get('X-Real-Ip', request.remote_addr)
或者, 使用werkzeug的middleware 文档

from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
return json & jsonp
import json
from flask import jsonify, Response, json

data = [] # or others
return jsonify(ok=True, data=data)

jsonp_callback = request.args.get('callback', '')
if jsonp_callback:
  return Response(
      "%s(%s);" % (jsonp_callback, json.dumps({'ok': True, 'data':data})),
      mimetype="text/javascript"
      )
return ok_jsonify(data)

Copy after login

配置读取方法

# create our little application :)
app = Flask(__name__)

# Load default config and override config from an environment variable
app.config.update(dict(
  DATABASE='/tmp/flaskr.db',
  DEBUG=True,
  SECRET_KEY='development key',
  USERNAME='admin',
  PASSWORD='default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)


------------------
# configuration
DATABASE = '/tmp/minitwit.db'
PER_PAGE = 30
DEBUG = True
SECRET_KEY = 'development key'

# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('MINITWIT_SETTINGS', silent=True)

Copy after login

几个不常用的方法

from flask import abort, flash

abort
if not session.get('logged_in'):
  abort(401)

flash
flash('New entry was successfully posted')

Copy after login

异步调用
想在flask的一个请求中处理异步, 除了使用消息系统, 可以用简单的线程处理

from threading import Thread

def async(f):
  def wrapper(*args, **kwargs):
    thr = Thread(target=f, args=args, kwargs=kwargs)
    thr.start()
  return wrapper

@async
def dosomething(call_args):
  print call_args


in a request handler, call `dosomething`
error handler
@app.errorhandler(404)
def not_found_error(error):
  return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(error):
  db.session.rollback()
  return render_template('500.html'), 500

Copy after login

项目配置
1.直接

app.config['HOST']='xxx.a.com'
print app.config.get('HOST')
Copy after login

2.环境变量

export MyAppConfig=/path/to/settings.cfg
app.config.from_envvar('MyAppConfig')
Copy after login

3.对象

 class Config(object):
   DEBUG = False
   TESTING = False
   DATABASE_URI = 'sqlite://:memory:'

 class ProductionConfig(Config):
   DATABASE_URI = 'mysql://user@localhost/foo'

 app.config.from_object(ProductionConfig)
 print app.config.get('DATABASE_URI') # mysql://user@localhost/foo

Copy after login

4.文件

# default_config.py
HOST = 'localhost'
PORT = 5000
DEBUG = True

app.config.from_pyfile('default_config.py')

Copy after login

EG. 一个create_app方法

from flask import Flask, g

def create_app(debug=settings.DEBUG):
  app = Flask(__name__,
        template_folder=settings.TEMPLATE_FOLDER,
        static_folder=settings.STATIC_FOLDER)

  app.register_blueprint(bp_test)

  app.jinja_env.globals.update(JINJA2_GLOBALS)
  app.jinja_env.filters.update(JINJA2_FILTERS)

  app.secret_key = 'PO+_)(*&678OUIJKKO#%_!(((%)))'

  @app.before_request
  def before_request():
    g.xxx = ...  #do some thing

  @app.teardown_request
  def teardown_request(exception):
    g.xxx = ...  #do some thing

  return app

app = create_app(settings.DEBUG)
host=settings.SERVER_IP
port=settings.SERVER_PORT
app.run(host=host, port=port)
change log:

2013-09-09 create
2014-10-25 update
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to control the size of XML converted to images? How to control the size of XML converted to images? Apr 02, 2025 pm 07:24 PM

To generate images through XML, you need to use graph libraries (such as Pillow and JFreeChart) as bridges to generate images based on metadata (size, color) in XML. The key to controlling the size of the image is to adjust the values ​​of the &lt;width&gt; and &lt;height&gt; tags in XML. However, in practical applications, the complexity of XML structure, the fineness of graph drawing, the speed of image generation and memory consumption, and the selection of image formats all have an impact on the generated image size. Therefore, it is necessary to have a deep understanding of XML structure, proficient in the graphics library, and consider factors such as optimization algorithms and image format selection.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

What is the process of converting XML into images? What is the process of converting XML into images? Apr 02, 2025 pm 08:24 PM

To convert XML images, you need to determine the XML data structure first, then select a suitable graphical library (such as Python's matplotlib) and method, select a visualization strategy based on the data structure, consider the data volume and image format, perform batch processing or use efficient libraries, and finally save it as PNG, JPEG, or SVG according to the needs.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

See all articles