flask獲取引數型別和請求響應
阿新 • • 發佈:2019-01-08
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表示方法