Guest User

Untitled

a guest
Apr 3rd, 2023
1,364
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. 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
  2.  
  3.  
  4. Response: Here's an example of a Flask post API to save a user's name, age, and occupation in a PostgreSQL database:
  5.  
  6. First, create a new Flask application and install the Flask-SQLAlchemy library, which allows you to easily work with a PostgreSQL database:
  7. from flask import Flask
  8. from flask_sqlalchemy import SQLAlchemy
  9.  
  10. app = Flask(__name__)
  11. app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@localhost/dbname'
  12. db = SQLAlchemy(app)
  13. Next, define the User model that corresponds to the user data you want to save in the database:
  14. class User(db.Model):
  15. id = db.Column(db.Integer, primary_key=True)
  16. name = db.Column(db.String(50))
  17. age = db.Column(db.Integer)
  18. occupation = db.Column(db.String(50))
  19. 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:
  20. @app.route('/user', methods=['POST'])
  21. def create_user():
  22. name = request.json['name']
  23. age = request.json['age']
  24. occupation = request.json['occupation']
  25. user = User(name=name, age=age, occupation=occupation)
  26. db.session.add(user)
  27. db.session.commit()
  28. return {'message': 'User created successfully'}
  29. Here's an example of a Flask GET API to retrieve the list of users saved in the database:
  30. @app.route('/user', methods=['GET'])
  31. def get_users():
  32. users = User.query.all()
  33. return jsonify([u.serialize() for u in users])
  34. 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