400:在 flask 登录时使用 hashlib 时出现错误请求

400: bad request when using hashlib on flask login

我正在设置一些基本的数据库哈希,但在设置时我收到了 400 错误请求。

这是我第一次使用哈希,我可以使用一些建议。我不打算在哈希上加盐。 HTML 方面有什么我遗漏的吗?

#!/usr/bin/env python
from flask import Flask, render_template, Markup, request, redirect, session, flash, url_for, flash, g
from flask_login import LoginManager,login_manager, current_user, login_required, login_user, logout_user, UserMixin, confirm_login, fresh_login_required
from flask_wtf import FlaskForm
from functools import wraps
from wtforms.validators import DataRequired
from wtforms import StringField
from socket import *            #required for sock address issue.
import mraa
from OpenSSL import SSL
import sys
import form
import time
import sqlite3
import hashlib
import logging

app = Flask(__name__)     #removing breaks everything.
@app.errorhandler(404)                         #  handles important errors    
                                               #   ^
def errorpage(e):                              #   ^      
    return render_template('404.html')         #   ^          \[T]/
@app.errorhandler(500)                         #   ^           |@| 
def errorpage500(e):                           #   ^           / \
    flash('error 500')                         #   ^     Praise the ASCII
                                               #       
def login_required(f):                         # makes login required modifier work                     
    @wraps(f)                                  #     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    def wrap(*args, **kwargs):                 #     @the only reason people keep using@
        if 'logged_in' in session:             #     @vi is they cant figure out how to@ 
            return f(*args, **kwargs)          #     @exit it.                         @
        else:                                  #     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                          
            flash('please login first.')       ##                         
            return redirect (url_for('index')) ################################                                  
    return wrap                                                          




def getHash(passText):
    hashPass=hashlib.sha512()
    hashPass.update(passtext)
    return(hashPass.hexdigest())


@app.route('/', methods=['GET','POST'])
def index():
    db = sqlite3.connect('sql.sql3')
    db.row_factory = sqlite3.Row
    epass=getHash(request.form['postPass'])
    query="select username, password from users where username=? and password=?"
    t=(request.form['postUser'], epass)
    cursor=db.cursor()
    cursor.execute(query,t)
    rows = cursor.fetchall()
    if len(rows) ==1:
        bodyText=request.form['postUser'] + " " + request.form["postPass"]
        bodyText=bodyText + "Success!"
        session['authenticated']='yes'
    else:
        bodyText = "incorrect login."   
    return render_template('/index.html')



if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=443, ssl_context='adhoc')

这是回溯的副本,但我不确定这是什么意思。

/usr/lib/python2.7/site-packages/cryptography/hazmat/backends/__init__.py:7: UserWarning: Module _functools was already imported from /usr/lib/python2.7/lib-dynload/_functools.so, but /usr/lib/python2.7/site-packages is being added to sys.path
  import pkg_resources
/usr/lib/python2.7/site-packages/cryptography/hazmat/backends/__init__.py:7: UserWarning: Module functools was already imported from /usr/lib/python2.7/functools.pyc, but /usr/lib/python2.7/site-packages is being added to sys.path
  import pkg_resources
Traceback (most recent call last):
  File "helloflask.py", line 69, in <module>
    app.logger.info(request.form)
  File "/usr/lib/python2.7/site-packages/werkzeug/local.py", line 343, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/lib/python2.7/site-packages/werkzeug/local.py", line 302, in _get_current_object
    return self.__local()
  File "/usr/lib/python2.7/site-packages/flask/globals.py", line 37, in _lookup_req_object
    raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

Here's the requested debug log

request.form['postPass']

这仅在 GET 请求中未填充 POST,因此这将是一个问题。

如果您希望在此视图中同时使用 GET 和 POST,我建议您这样做:

@app.route('/', methods=['GET','POST'])
def index():
    if request.method == 'POST':
        #process the posted data
        return something

    if request.method == 'GET':
        #do something else
        return something_else

你的回溯也告诉你这是一个问题:

Traceback (most recent call last):
  File "helloflask.py", line 69, in <module>
    app.logger.info(request.form)

...

RuntimeError: Working outside of request context.

在第 69 行,您试图记录一个 request 对象,该对象仅存在于用户请求的上下文中。首先注释掉这一行