Forums

KeyError

Hello everyone, i need help, i'm stuck with this problem for days now. However this is my first time deploying an app with pythonanywhere. My server side api-s alongisde my db are hosted on pythonanywhere and my frontend and everything else is on Netlify.

error log here:

2019-09-30 17:35:54,003: Exception on /users [POST] Traceback (most recent call last): File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app response = self.full_dispatch_request() File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(args, *kwargs))) File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise raise value File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request rv = self.dispatch_request() File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request return self.view_functionsrule.endpoint File "/home/egze/deploy/main.py", line 34, in login flask.request.json) File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/pymysql/cursors.py", line 168, in execute query = self.mogrify(query, args) File "/home/egze/.virtualenvs/deploy/lib/python3.7/site-packages/pymysql/cursors.py", line 147, in mogrify query = query % self._escape_args(args, conn) KeyError: 'user_email'

Api call that seems to have an error:

@app.route('/users', methods=['POST'])
def register_user():
    db = mysql_db.get_db()
    cursor = db.cursor()
    cursor.execute("INSERT INTO users (user_name, user_country, user_email, user_password) VALUES(%(user_name)s, %(user_country)s, %(user_email)s, %(user_password)s)", flask.request.json)
    db.commit()
    return "", 201

And call from frontend(react):

  register = event => {
    event.preventDefault();
    axios
      .post(
        "https://egze.pythonanywhere.com/users",
        { user_name: this.nameInput.value },
        { user_country: this.countryInput.value },
        { user_email: this.emailInput.value },
        { user_password: this.passwordInput.value }
      )
      .then(response => {
        this.props.userRegister(response);
        this.props.history.push("/login");
      })
      .catch(
        error => console.log(error.response),
        swal("Something went wrong \n Try again later.", {
          button: false
        })
      );
  };

Thank you in advance!

Small digression:

Almost the same calls:

@app.route('/jobs', methods=["POST"])
def add_job():
    db = mysql_db.get_db()
    cursor = db.cursor()
    cursor.execute("INSERT INTO jobs (job_name, job_city, job_image, job_level, job_type, job_additional) VALUES(%(job_name)s, %(job_city)s, %(job_image)s, %(job_level)s, %(job_type)s,%(job_additional)s)", flask.request.json)
    db.commit()
    return "", 201

Frontend:

  addJob = event => {
    event.preventDefault();
    let job = {
      job_name: this.nameInput.value,
      job_city: this.cityInput.value,
      job_image: this.imageInput.value,
      job_level: this.jobLevelInput.value,
      job_type: this.jobTypeInput.value,
      job_additional: this.reqInput.value,
    };
    axios
      .post("https://egze.pythonanywhere.com/jobs", job)
      .then(response => {
        this.props.addJobState(job);
        swal("You added a new job.", {
          button: false
        });
      })
      .catch(error =>
        swal("Something went wrong \n Try again later.", {
          button: false
        })
      );
  };

Its absolutely the same effect if u wrap data in object and assign that object to variable or just to send 'nameless' object if u wonder about difference between two frontend calls. Except that difference everything else is almost the same but this one works.

Add some debugging code both on frontend and backend to see what is the content of post and flask.response.json in both sides.

Here is output on frontend side for:

  register = event => {
    event.preventDefault();
    let newUser = {
      user_name: this.nameInput.value,
      user_country: this.countryInput.value,
      user_email: this.emailInput.value,
      user_password: this.passwordInput.value
    };
    axios
      .post("https://egze.pythonanywhere.com/users", {
        newUser
      })
      .then(response => {
        this.props.userRegister(response);
        this.props.history.push("/login");
      })
      .catch(
        error => console.log(error.response),
        console.log(newUser),
        swal("Something went wrong \n Try again later.", {
          button: false
        })
      );
  };

console.log(newUser):

{user_name: "John", user_country: "Cuba", user_email: "john@gmail.com", user_password: "john123"}

consol.log(error.response)

    {data: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final/…ded or there is an error in the application.</p>↵", status: 500, statusText: "INTERNAL SERVER ERROR", headers: {…}, config: {…}, …}
config:
adapter: ƒ xhrAdapter(config)
data: "{"newUser":{"user_name":"John","user_country":"Cuba","user_email":"john@gmail.com","user_password":"john123"}}"
headers: {Accept: "application/json, text/plain, */*", Content-Type: "application/json;charset=utf-8"}
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: [ƒ]
transformResponse: [ƒ]
url: "https://egze.pythonanywhere.com/users"
validateStatus: ƒ validateStatus(status)
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object
data: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><title>500 Internal Server Error</title><h1>Internal Server Error</h1><p>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.</p>↵"
headers: {content-length: "290", content-type: "text/html"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 500
statusText: "INTERNAL SERVER ERROR"
__proto__: Object

To be honest i don't know how to print from server side, or maybe i do, but i'm not getting anything, i tried print(flask.request.json) or simply anything like print("print from register_user") but nothing is showing up in server.log or error.log where i believe it should.

You need to print to sys.stderr for that output to appear in the error log.

Ok guys a little update. I fixed this KeyError, but now i'm getting 401 unauthorized error on this same POST request(register), whats funny it works grate locally, when i host my app on localhost, but when server is deployed here on pythonanywhere it throws this error. Any solution?

Code is same as in above example i gave, and one more thing in request headers for this request i have Provisional headers are shown.

Ty.

Do you have "Password protection" enabled on your web app? If you do, then you need to send the authorisation headers with your request.

Good evening. I get the following error:

2020-08-24 18:02:05,630: Exception on / [POST]
Traceback (most recent call last):
  File "/home/semiglazovTeS1990/venv/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/semiglazovTeS1990/venv/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/semiglazovTeS1990/venv/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/semiglazovTeS1990/venv/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/semiglazovTeS1990/venv/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/semiglazovTeS1990/venv/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/semiglazovTeS1990/bot/main.py", line 67, in index
    message=response["message"]["text"]
KeyError: 'text'

I cannot restart my application to start working again. Can you restart it or tell me how to do it?

[edit by admin: formatting]

My application- semiglazovTeS1990.pythonanywhere.com

You can restart your website by using the green button on the "Web" page. Once you do that, any new errors will appear at the bottom of the error log file.