AttributeError: 'function' object has no attribute 'get' - Flask Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

AttributeError: 'function' object has no attribute 'get' - Flask Python

Just started learning Flask. I have created a simple app with 2 endpoints. I have a dictionary that contains posts. I want to get a particular post from posts dictionary and return it to user. Problem: When i send a request to '/posts/1' endpoint, i get following error message "AttributeError: 'function' object has no attribute 'get'" at this line post = posts.get(post_id) What's the problem here and how can i fix it? Here's my code from flask import Flask app = Flask(__name__) posts = { 0: { 'title': 'Hello World', 'content': 'This is my first blog post' }, 1: { 'title': '2nd BLog Post', 'content': 'This is my second blog post' } } @app.route('/') def home(): return 'Hello World!' @app.route('/posts/<int:post_id>') def posts(post_id): post = posts.get(post_id) return f'Post\n\nTitle: {post["title"]}\nContent\n{post["content"]}' if __name__ == '__main__': app.run(debug=True)

11th Nov 2019, 4:28 PM
Yousaf
Yousaf - avatar
1 Answer
+ 10
It looks to me like you are overwriting the posts dictionary when defining the posts function (the error is a giveaway for that) Try renaming the function to something else: def get_post(post_id): .....
11th Nov 2019, 5:25 PM
Burey
Burey - avatar