是什么导致这个错误的请求

时间:2015-09-22 00:31:00

标签: python flask

我的烧瓶应用程序视图功能:

@app.route("/database_filter", methods=['POST', 'GET'])
def database_filter():

    error = ''
    points = ''
    time_search = False
    hdop_search = False
    points_len = 0
    conn = sqlite3.connect(database)
    c = conn.cursor()

    if request.method == 'POST':

        '''If all datetime forms are filled out and the start is not after the end, set time_search True'''

        if request.form['startdate'] and \
            request.form['starttime'] and \
            request.form['enddate'] and \
            request.form['endtime']:
            start = request.form['startdate'] + 'T' + request.form['starttime']
            end = request.form['enddate'] + 'T' + request.form['endtime']
            if datetime_object(start) > datetime_object(end):
                error = '**Start value selected must occur before End value.'
                return render_template('database_filter.html', error=error)
            else:
                time_search = True
                print 'time search: ' + str(time_search)

        if request.form['hdop_oper'] and request.form['hdop']:
            hdop_search = True
            print 'hdop and hdop_oper exist'
            hdop_oper = request.form['hdop_oper']
            hdop = float(request.form['hdop'])


        '''Prepare search statement based on forms selected'''

        if time_search == True and hdop_search == True:
            print 'Time and hdop:'
            search_string = 'SELECT * from (SELECT TSTAMP, LAT, LON, FILE, HDOP FROM POINTS WHERE TSTAMP BETWEEN "%s" and "%s") WHERE HDOP %s %.1f ORDER BY TSTAMP DESC'%(start, end, hdop_oper, hdop)
            print search_string

        if time_search == False and hdop_search == True:
            print 'Hdop only'
            search_string = 'SELECT TSTAMP, LAT, LON, FILE, HDOP FROM POINTS WHERE HDOP %s %.1f ORDER BY TSTAMP DESC'%(hdop_oper, hdop)
            print search_string

        if time_search == True and hdop_search == False:
            print 'Time only'
            search_string = 'SELECT TSTAMP, LAT, LON, FILE FROM POINTS WHERE TSTAMP BETWEEN "%s" and "%s" ORDER BY TSTAMP DESC'%(start, end)
            print search_string

        if time_search == False and hdop_search == False:
            print 'no time no hdop'
            error = 'No search criteria selected.'
            search_string = 'SELECT TSTAMP, LAT, LON, FILE FROM POINTS ORDER BY TSTAMP DESC'
            print search_string

        '''Execute SQL search and return dictionary of points'''

        cur = c.execute(search_string)

        points = [dict(TSTAMP=row[0][11:20], DATE=row[0][0:10],
            LAT=row[1],
            LON=row[2],
            FILE = row[3]) for row in cur.fetchall()]

        points_len = len(points)

        return render_template('database_filter.html', error=error, points=points, points_len=points_len)

    return render_template('database_filter.html', error=error, points=points, points_len=points_len)

用于呈现它的html页面:

<!--Filter Search criteria form -->
<form action="database_filter" id="database_filter" method="post">
    <p id="basicExample">
        <!-- Date/time range form; requires js library at bottom -->
        <input type="test" placeholder="Start Date" class="date start" name="startdate" value="{{ request.form.startdate }}">
        <input type="test" placeholder="Start Time" class="time start" name="starttime" value="{{ request.form.starttime }}">  to  
        <input type="test" placeholder="End Date" class="date end" name="enddate" value="{{ request.form.enddate }}">
        <input type="test" placeholder="End Time" class="time end" name="endtime" value="{{ request.form.endtime }}">
    </p>

    <br>

    <strong>HDOP Filter</strong><br>
    <select name="hdop_filter">
        <option>HDOP</option>
    </select>


    <select id="hdop_oper" name="hdop_oper">
        <option>&lt;</option>
        <option>&gt;</option>
        <option>&ge;</option>
        <option>&le;</option>
        <option>&#61;</option>
        <option selected disabled value=''></option>
    </select>


        HDOP Value;
        <input type="number" id="hdop" name="hdop" min="0" max="2" step=".1">


<input class="btn-default" type="submit" value="Update Search">
<br>
<strong>*Number of points found: </strong>{{points_len}}
</form>
<br>
<br>





    <h4>{{error}}</h4>
    <br>
    <p><strong>Date =</strong> YYYY-MM-DD  <strong>Time =</strong> HH:MM:SS</p>


    {% for point in points %}
    <pre>
    <strong>Date:</strong> {{ point.DATE }} <strong>Time:</strong> {{ point.TSTAMP }}
    <strong>Latitude:</strong>  {{ point.LAT }}  <strong>Longitude:</strong> {{ point.LON }}
    <strong>Source File:</strong> {{point.FILE }}</pre>
    {% endfor %}





            <!-- datetime formatting https://codex.wordpress.org/Formatting_Date_and_Time -->
            <!-- http://jonthornton.github.io/jquery-timepicker/ -->
            <script>
                $('#basicExample .time').timepicker({
                    'scrollDefault': 'now',
                    'showDuration': true,
                    'timeFormat': 'H:i:s'
                });

                $('#basicExample .date').datepicker({
                    'scrollDefault': 'now',
                    'format': 'yyyy-mm-dd',
                    'autoclose': true
                });
                $(document).ready(ready);

                var basicExampleEl = document.getElementById('basicExample');
                var datepair = new Datepair(basicExampleEl);
            </script>
            <!-- END Script for date time picker -->

每当我选择所有日期时间值而没有hdop值时,flask会返回&#34;错误请求&#34;。但是,如果我只选择hdop过滤器信息而没有日期时间,则会按预期返回数据。有线索吗?除了他们的表单类型之外,我认为两者没有区别。

感谢您的关注!

1 个答案:

答案 0 :(得分:0)

错误在方法调用中,以获取hdop_oper和hdop的表单值。

在Flask中获取可选表单的正确方法是使用以下内容:

if request.form.get('hdop_oper') and request.form.get('hdop'):

而不是:

if request.form['hdop_oper'] and request.form['hdop']:

我想指出Flask的追溯功能不会引发'keyerror'异常,让你猜出真正的问题是什么。

我知道SO不是用于调试你的代码,但我确信一些Flask专业人员会在这里发现这个Flask异常。如果不出意外,有人可能会在将来发现这有用。