【代码】Flask+Web开发:基于Python的Web应用开发实战

本文介绍了在Python 2和3环境下使用Flask-Script遇到的问题及解决办法,包括虚拟环境的创建与管理,如venv的安装与使用。此外,还涉及模板继承、web表单处理、数据库迁移、Jinja2过滤器的自定义以及防止SQL注入等Flask应用开发的关键知识点。
摘要由CSDN通过智能技术生成

第2章 程序的基本结构

# encoding=utf-8
from flask import Flask, request, redirect, make_response
from flask_script import Manager


app = Flask(__name__)
# 添加命令行解析功能
manager = Manager(app)

@app.route('/')
def index():
	# request object
	user_agent = request.headers.get('User-Agent')
	return '<h1>hello world!</h1>\r\n<p>Your browser is {}</p>'.format(user_agent)

	# return response, status code
	# return '<h1>bad request</h1>',400

	# redirect
	# return redirect('http://www.baidu.com')

	# make response
	# response = make_response('<h1>This document carries a cookie!</h1>')
	# response.set_cookie('answer', '42')
	# return response

@app.route('/user/<name>')
def user(name):
	return '<h1>hello, {}</h2>'.format(name)

@app.route('/user/<id>')
def get_user(id):
	user = load_user(id)
	if not user:
		abort(404)
	return '<h1>hello, {}</h1>'.format(user.name)


if __name__ == '__main__':
	# app.run(debug=True)
	manager.run()

2.6 flask扩展

学到了扩展,Flask-Script别说使用,安装先喝了一壶

python2下 flask-script的情况

先看看书中做法:

安装方式
(venv) $ pip install flask-script
导入方式:
示例 2-3 hello.py:使用 Flask-Script
from flask.ext.script import Manager

环境:python 2.7.6,flask 1.0.2,所以应该不是版本的冲突吧?
报错:ImportError: No module named ext.script
更换导入方式:from flask_script import Manager
依然报错ImportError
deactivate 退出虚拟环境再source venv/bin/activate进入,然并卵

看到一贴:
no module named flask.ext.moment
在虚拟环境(取名:venv)下继续安装:

pip install Flask-Script(显示:Requirement already satisfied)
pip install Flask-Moment

依然报错:ImportError: No module named ext.script
更换导入方式:from flask_script import Manager
于是成功了吧?:

usage: hello.py [-?] {shell,runserver} ...

positional arguments:
  {shell,runserver}
    shell            Runs a Python shell inside Flask application context.
    runserver        Runs the Flask development server i.e. app.run()

optional arguments:
  -?, --help         show this help message and exit

python3下 flask-script的情况

后来使用python3的venv安装了虚拟环境(取名:py3)在py3环境下,导入报错,以上方法均不起作用,可见虚拟环境(py3)不被支持。。。
用python2的virtualenv安装虚拟环境(取名:py),在py环境下,运行python hello.py报错,运行python3 hello.py成功,显示:usage: hello.py [-?] {shell,runserver} …
不在虚拟环境py/py3下,运行python/python2/python3 hello.py均成功,所以说是虚拟环境的锅么。。。。。。

python3的安装,然并卵

默默去安装了3.6。。。Ubuntu怎样安装Python3.6,半路get到新技能apt-fast
因为安装好了py3.6,于是在新建文件夹使拥venv开启虚拟环境

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值