Issue
I have a small flask app that I’m using to import jobs from a database. The route I use for importing the jobs is as follows (job_details is a submit button in a form for each individual job that passes the job):
@app.route("/job-import", methods=["POST"])
def job_import():
if "loggedin" in session:
if request.method == 'POST':
job = request.form['job_details']
# Job comes in string format, therefore needs to be converted to DICT
job = ast.literal_eval(job)
...
I want to convert the string I get from request.form['job_details']
to a dict so I can then parse it and access the values via job['description'], job['title']
etc. However, I keep getting a ‘TypeError: string indices must be integers’ error. I am sure it is being passed as a string, and as far as I can find ast.literal_eval()
should convert the string to a dict, however this is clearly not the case. Why is this?
Some sample input for a job from my app:
"{'id': 3, 'date': datetime.date(2022, 2, 3), 'job_title': 'Cool title', 'contact_name': 'Mr Cool', 'contact_email': '[email protected]', 'location': 'Coolville', 'expiry_date': datetime.date(2022, 5, 1), 'salary': None, 'twitter': None, 'listing_type': None, 'description': 'a cool job for cool people to do cool things', 'url': 'cooljobs.cool', 'logo': None, 'status': None}"
Full traceback:
return self.wsgi_app(environ, start_response)
File "", line 2450, in wsgi_app response = self.handle_exception(e)
File "", line 1867, in handle_exception reraise(exc_type, exc_value, tb) File "", line 39, in reraise raise value
File "", line 2447, in wsgi_app response = self.full_dispatch_request()
File "", line 1952, in full_dispatch_request rv = self.handle_user_exception(e)
File "", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb)
File "", line 39, in reraise raise value
File "", line 1950, in full_dispatch_request rv = self.dispatch_request() File "", line 1936, in dispatch_request return self.view_functionsrule.endpoint
File "", line 57, in app if job[‘listing_type’] == "Basic job listing (free)":
Solution
I have since worked on this and solved the issue. In all honesty, I am not sure how. I ended up using ast.literal_eval and this has worked thus far and my program is working correctly as of now. I did not however change the datetime.date value in the database, although in future I think I will avoid this type as a rule of thumb.
Thank you to everyone who gave advice.
Answered By – Sterling
Answer Checked By – Candace Johnson (BugsFixing Volunteer)