Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Query: Write a flask post api to save name, age an occupation in a postgres database. Also write a get api to retrieve the list of user saved in db
- Response: Here's an example of a Flask post API to save a user's name, age, and occupation in a PostgreSQL database:
- First, create a new Flask application and install the Flask-SQLAlchemy library, which allows you to easily work with a PostgreSQL database:
- from flask import Flask
- from flask_sqlalchemy import SQLAlchemy
- app = Flask(__name__)
- app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@localhost/dbname'
- db = SQLAlchemy(app)
- Next, define the User model that corresponds to the user data you want to save in the database:
- class User(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- name = db.Column(db.String(50))
- age = db.Column(db.Integer)
- occupation = db.Column(db.String(50))
- In the route that handles the POST request, use the db.session.add() method to add the new user to the database and then call db.session.commit() to save the changes:
- @app.route('/user', methods=['POST'])
- def create_user():
- name = request.json['name']
- age = request.json['age']
- occupation = request.json['occupation']
- user = User(name=name, age=age, occupation=occupation)
- db.session.add(user)
- db.session.commit()
- return {'message': 'User created successfully'}
- Here's an example of a Flask GET API to retrieve the list of users saved in the database:
- @app.route('/user', methods=['GET'])
- def get_users():
- users = User.query.all()
- return jsonify([u.serialize() for u in users])
- The above code is an example, you may need to modify it based on your specific requirements.
Advertisement
Add Comment
Please, Sign In to add comment