FLASK 和 Postman 应用程序中的 REST API:
代码:
from flask_sqlalchemy import SQLAlchemy
from flask import Flask,render_template,request,jsonify,json
import psycopg2
import psycopg2.extras
app = Flask(__name__)
db = SQLAlchemy()
conn = psycopg2.connect("postgresql://postgres:postgres@localhost:5432/country")
cr = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
@app.route('/', methods=['GET'])
def test():
return jsonify({
'message': 'Welcome'
})
@app.errorhandler(404)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404
##### Countries ######
@app.route('/country/all', methods=['GET'])
def country():
cr.execute('select * from country')
country = cr.fetchall()
countries = []
for row in country:
countries.append(dict(row))
return jsonify(countries)
if __name__ == '__main__':
app.run(debug=True, port=8080)
结果:
**