MySQL 连接不可用且 werkzeug 密钥错误

问题描述 投票:0回答:1

我有一个带有 Web 表单的简单 Flask 应用程序。当我提交Web表单,然后将数据上传到mysql时,有时可以,但有时不行。这在本地和当我在公共网址上部署到谷歌云时都会发生(

example.com
)。

该表格位于

templates/auth/signup.html
,是

    <form method="POST" action="/signupSubmit">
            <label for="firstname">First name: </label>
            <input type="text" placeholder="John" name="firstname" id="firstname" required></input>
            <br /> <br />
            <label for="lastname">Last name: </label>
            <input type="text" placeholder="Smith" name="lastname" id="lastname" required></input>
            <br /> <br />
            <label for="phone">Phone number: </label>
            <input type="tel" placeholder="412-555-1234" name="phone" id="phone" required></input>
            <br /> <br />
            <label type="text" name="email" id="email">Email: </label>
            <input type="email" placeholder="[email protected]" name="email" id="email" required></input>
            <br /> <br/>
            <button type="submit">Submit</button>
    </form>

main.py
中的服务器逻辑是

from flask import Flask, render_template, request
from jinja2 import Environment, FileSystemLoader
from dotenv import load_dotenv
import os, mysql.connector, stripe

load_dotenv()

...

@app.route("/auth/signup", methods=['GET']) 
def signup():
    return render_template('auth/signup.html')

dataBase = mysql.connector.connect(
    host=os.environ['DB_HOST'],
    password=os.environ['DB_PASSWORD'],
    user=os.environ['DB_USER'],
    port=os.environ['DB_PORT'],
    database=os.environ['DB_DATABASE'],
    connection_timeout=3600
)

def saveSQLthenStripe(firstName, lastName, email, phone):
    query = "INSERT INTO users (firstname, lastname, email, phone) VALUES (%s, %s, %s, %s)" 
    vals = (firstName, lastName, email, phone) 
    cursorObject = dataBase.cursor()
    cursorObject.execute(query, vals) 
    dataBase.commit() 
    dataBase.close()
    thenStripe(firstName, lastName, email, phone)

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

    print(request.form['firstname'])
    if "firstname" in request.form:
        print("first name there")
    else:
        print("first name not there")
    fname = request.form['firstname'] 
    lname = request.form['lastname']
    email = request.form['email']
    phone = request.form['phone']
    saveSQLthenStripe(fname, lname, email, phone) 
    return render_template('auth/success.html', title="Submit successful")

举个刚刚发生的例子.. 我使用

python main.py
在本地运行应用程序,提交表单,上传到 mysql,浏览器没有错误。终端打印

127.0.0.1 - - [24/Jan/2024 09:27:54] "GET /auth/signup HTTP/1.1" 200 -
test1
first name there

但是,我去了邮递员,在服务器仍在运行的情况下,用键

post
http://localhost:8080/signupSubmit
firstname
lastname
phone
发出了
email
请求,它返回了此错误

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this
        server could not understand.
        KeyError: &#39;firstname&#39;

当我的终端同时打印时

    raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.        
KeyError: 'firstname'

然后,在服务器仍在运行的情况下,我返回浏览器

http://localhost:8080/auth/signup
并提交包含不同信息的表单,并从浏览器收到此错误

OperationalError
mysql.connector.errors.OperationalError: MySQL Connection not available.

用我的终端打印

127.0.0.1 - - [24/Jan/2024 09:29:29] "GET /auth/signup HTTP/1.1" 200 -
test2
first name there

我去了邮递员,服务器仍然在运行,做了发布请求并收到了与之前相同的错误

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this
        server could not understand.
        KeyError: &#39;firstname&#39;

与终端打印相同

KeyError: 'firstname'
.

在实时版本(

example.com
)上,我可以一次提交表单,没有错误,但浏览器每次连续尝试都会返回

Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

开发工具显示 500。

在进行另一项测试时,提交表单后,我的终端打印了(带有完整的打印语句):

raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.        
KeyError: 'firstname'
first name there
last name there
email there
phone there
INSERT INTO users (firstname, lastname, email, phone) VALUES (%s, %s, %s, %s)
('somefirst', 'somelast', '[email protected]', '3333')
<mysql.connector.connection_cext.CMySQLConnection object at ***********>
<class 'mysql.connector.connection_cext.CMySQLConnection'>
127.0.0.1 - - [24/Jan/2024 08:39:30] "POST /signupSubmit HTTP/1.1" 200 -

直接反驳我没有

firstname

我为mysql运行了

SHOW PROCESSLIST;
并且它返回了

Id    | User           | Host     | db   | Command  | Time  |  State                | Info 
-------------------------------------------------------------------------------------------
5      event_scheduler  localhost  null   Daemon      6941326  Waiting on empty que  null
26362  rdsadmin         localhost  null   Sleep       7                              null

还有我的互联网公司的东西。

我很困惑为什么在提交一份表单后mysql没有连接,因为我认为这就是最终导致错误的原因。

目录结构

myproject
|
|--env
|   |
|   +--Include
|   +--Lib         
|   +--Scripts
|   +--pyvenv.cfg
|
|--static
|--templates
|--.env 
|--.flaskenv 
|--.gitignore
|--app.yaml
|--main.py
|--requirements.txt
python mysql flask postman werkzeug
1个回答
0
投票

我意识到我需要将dataBase放入saveSQL然后Stripe中。当我最初使用

python main.py
运行应用程序时,它正在创建连接,但之后就没有了。

那么

def saveSQLthenStripe(firstName, lastName, email, phone):
    dataBase = mysql.connector.connect(
        host=os.environ['DB_HOST'],
        password=os.environ['DB_PASSWORD'],
        user=os.environ['DB_USER'],
        port=os.environ['DB_PORT'],
        database=os.environ['DB_DATABASE'],
        connection_timeout=3600
    )
    query = "INSERT INTO users (firstname, lastname, email, phone) VALUES (%s, %s, %s, %s)" 
    ...

我仍然没有弄清楚邮递员错误,但我的应用程序仍然在本地和生产中运行(

example.com
)。

© www.soinside.com 2019 - 2024. All rights reserved.