Building RESTful APIs with Flask in PyCharm
Building RESTful APIs with Flask in PyCharm
Installing packages
Once your virtualenv is ready, click the “Install” button to begin installing packages. We’ll be installing three packages for our project:
- Flask (install either by pycharms STTINGS-----PYTHON INTERPRETOR (+))
- Flask-Restless (for building the RESTful API)
- Flask-SQLAlchemy (for connecting to our database) || OR MySQLdb
In Pycharms (Main.py):write below code here change parameters as per your database:
import flask
from flask import Flask, json, request, jsonify
from flask_mysqldb import MySQL, MySQLdb
# pip install flask-mysqldb https://github.com/alexferl/flask-mysqldbapp = Flask(__name__)
app.secret_key = "2021"
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'entry_system'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
@app.route('/')
def index():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM visit_mas")
rv = cur.fetchall()
employee = []
content = {}
for result in rv:
content = {'pass_no': result['pass_no'], 'mobile_no': result['mobile_no'],
'visit_purpose': result['visit_purpose']}
employee.append(content)
content = {}
return jsonify(employee)
if __name__ == "__main__":
app.run(debug=True)
Then Run Pycharms
CONSOLE WILL SHOW IN PYCHARMS S:
C:\Users\RCF\PycharmProjects\pythonProject\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2020.3.2\plugins\python-ce\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 65023 --file C:/Users/RCF/PycharmProjects/pythonProject/main.py
Connected to pydev debugger (build 203.6682.179)
* Serving Flask app "main" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 239-188-691
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
OPEN IN BROWSER : http://127.0.0.1:5000/:::::
[ { "mobile_no": "213223421", "pass_no": 124, "visit_purpose": "test" } ]REMARKS:1.use Double Underscope else will give name error in
__name__ == "__main__":
Comments
Post a Comment