flask重要的两种请求:
- GET (大多是url请求)
- POST (大多是表单的提交)
(1)GET请求的的参数类型:
- str(默认)
- int
- float
- path
- uuid
# 没规定,默认(str)
@blue.route('/hello/<name>/')
def hello_mian(name):
return 'hello %s' % (name)
# int 参数
@blue.route('/helloint/<int:id>/')
def hello_int(id):
return 'hello int:%s' % (id)
# float 参数
@blue.route('/getfloat/<float:price>/')
def hello_float(price):
return 'float:%s' % (price)
# string 参数
@blue.route('/getstr/<string:name>/')
def hello_name(name):
return 'hello name:%s' % name
# path 参数
@blue.route('/getpath/<path:url_path>/')
def hello_path(url_path):
return 'path: %s' % url_path
# uuid 参数
@blue.route('/getuuid/')
def get_uuid():
a = uuid.uuid4()
return str(a)
# uuid参数
@blue.route('/getbyuuid/<uuid:uu>/')
def hello_uuid(uu):
return 'uu:%s' % uu
方法怎么获取GET请求的参数:
例如请求:127.0.0.1/index/?id=1&name=coco
Djngo 获取GET请求的参数:
def helloParams(request):
id = request.GET.get('id')
name = request.GET.get('name')
flask 获取GET请求的参数
@blue.route('/getrequest/', methods=['GET', 'POST'])
def get_request():
if request.method == 'GET':
# args = request.args
id = request.args.getlist('id')
name = request.args.getlist('name')
Djngo 获取POST请求的值:
例如:
<input type='text' name='username'>
<input type='password' name='password'>
def helloParams(request):
id = request.POST.get('username')
name = request.POST.get('password')
flask 获取POST请求的参数
@blue.route('/getrequest/', methods=['GET', 'POST'])
def get_request():
if request.method == 'POST':
#form = request.form
username = request.form.getlist('username')
password = request.form.getlist('password')
(2)响应(response)
Django响应:
- HttpResponse
- render(返回页面)
- HttpResponseRedirect (跳转页面)
- reverse (重定向(可以传参数))
return HttpResponse('张三')
return render(request, 'cart/cart.html', {'user_carts': user_cart, 'goods_sum': sum, 'all_select': select})
return HttpResponseRedirect('/log/login/')
return HttpResponseRedirect(reverse('cart:showordershop', args=(str(order.id),)))
flask响应:
- make_response
- render_template(和Django的render相同)
- redirect(和django的HttpResponseRedirect 相同)
- url_for(和django的 reverse差不多)
# 响应
@blue.route('/makeresponse/')
def make_responses():
temp = render_template('hello.html')
response = make_response(temp)
return response
# 跳转页面
@blue.route('/redirect/')
def make_redirect():
# 第一种方法
# return redirect('/index/')
# 第二种方法
return redirect(url_for('first.hello')) # first表示蓝图名字,hello表示方法