如何使用Flask从Python中获取表单中的数据

时间:2017-11-29 09:27:35

标签: python flask flask-wtforms

这是我的runn.py代码:

@app.route('/', methods=['GET', 'POST'])
def index():
    with app.open_resource('static/docs/student1.txt') as f1:
       content1 = f1.read()
    with app.open_resource('static/docs/student2.txt') as f2:
       content2 = f2.read()
    with app.open_resource('static/docs/student3.txt') as f3:
       content3 = f3.read()
    with app.open_resource('static/docs/student4.txt') as f4:
       content4 = f4.read()

    contents = [content1, content2, content3, content4]
    students = ['Student1','Student2','Student3','Student4']

    selected_student = requests.GET['student_form']   
    if (selected_student == 'Student2'):
      content_selected = content2
    elif (selected_student == 'Student3'):
      content_selected = content3
    elif (selected_student == 'Student4'):
      content_selected = content4
    else:
      content_selected = content1
    return render_template('index.html', students = students, content_selected=content_selected)

这是我的HTML代码:

<form action="runn" name='frm' method='POST'>    
  <h3>Which Student</h3>
  <select name="student_form" method="GET" action="/">
    <option value="{{students[0]}}" selected>{{students[0]}}</option>
    {% for student in students[1:] %}
    <option value="{{student}}">{{student}}</option>
  {% endfor %}
  </select>

  <input type='submit' value='submit'>
</form>

<div>
  <pre> {{ content_selected }}</pre>
</div>

我无法获取要在视图中显示的表单数据。 错误是:

  

AttributeError:&#39; module&#39;对象没有属性&#39; GET&#39;

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

selected_student = request.form.get('student_form')

答案 1 :(得分:0)

我认为您可以使用request模块。

@api.route('/resource', methods=['GET', 'POST'])

def ticket(*args, **kwargs):
  if(request.method == 'POST'):
    return ResourceController.create(request)
  elif(request.method == 'GET'):
    return ResourceController.index()

在控制器内部

def create(request):
    resource_type = request.form['resource_type'] 
    ...
    ...