Skip to content

Instantly share code, notes, and snippets.

@souravs17031999
Created August 19, 2021 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souravs17031999/d840249e1d4b09de6efa181ff3932c77 to your computer and use it in GitHub Desktop.
Save souravs17031999/d840249e1d4b09de6efa181ff3932c77 to your computer and use it in GitHub Desktop.
from flask import Flask, json, jsonify, request, Response, Blueprint
import psycopg2
app = Flask(__name__)
user = Blueprint('user', __name__)
DATABASE_URL = "postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]"
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
@user.route('/fetch-info')
def fetch_user_info():
user_id = request.args.get("user_id")
cursor = conn.cursor()
affected_count = 0
query = ("SELECT * FROM users WHERE user_id = %s")
try:
cursor.execute(query, (user_id,))
print(cursor.query.decode())
print(f"{affected_count} rows affected")
db_data = cursor.fetchone()
affected_count = cursor.rowcount
print("DB DATA : ", db_data)
except Exception as e:
print(e)
finally:
cursor.close()
response = {}
if affected_count != 0:
response["status"] = "success"
response["message"] = "Users fetched successfully !"
response["user_data"] = {
"firstname": db_data[0], "lastname": db_data[1]}
return jsonify(response), 200
else:
response["status"] = "failure"
response["message"] = "No active users found in records !"
return jsonify(response), 404
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment