Fetching MongoDB data in Flask using pyMongo - python

I need help with fetching data from a MongoDB collection in a simple Flask webpage. I've been trying to figure out how to fetch it but it has been of no help. My JSON data is an array of documents with 3 nested fields and I have attached it with the question. I'm trying to fetch all the data of the JSON template at first but I've been unable to. Once I know, I'll fetch the individual array.
Here is my Flask code:
from flask import Flask
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient("mongodb://localhost:27017/")
db = client.Learning
todos = db.data
#app.route('/')
def lists():
for x in todos.find():
y = print(x)
return ""
if __name__ == '__main__':
app.run()
And this is my data structure for the MongoDB data:
Any help or hint will be really appreciated so I can know how to fetch the data. Do I have to use HTML? If so, how can I fetch the arrays within arrays with HTML?

You could try using Flask-PyMongo.
It works like this:
from flask import Flask
from flask_pymongo import PyMongo
from flask.json import jsonify
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/Learning"
mongo = PyMongo(app)
#app.route("/")
def lists():
print([i for x in mongo.db.data.find({})])
return jsonify([i for i in mongo.db.data.find({})])
if __name__ == '__main__':
app.run()

Related

Issue with simple python API in flask. Trying to create a post method to add json data to a list

I am trying to build a simple flask api to post json data to a list (eventually with be redshift but this is just a simple test program).
I have attached the api code first followed by the code to send data.
I am getting internal server error issues when running the second script.
The code seems very simple though and I cannot figure out what is wrong.
from flask_restful import Api, Resource
from flask import request
app = Flask(__name__)
api = Api(app)
audit_log = []
class audit(Resource):
#def get (self):
#return {"data":"HelloWorld"}
def put (self):
new_item = request.get_json()
audit_log.append(new_item)
return new_item
api.add_resource(audit,"/")
app.run()
import requests
BASE = "HTTP://127.0.0.1:5000/"
response = requests.put(BASE, params = {'auditid' : 'xyz', 'jobname' : 'abc'})
print (response.json())
It seems that you haven't imported the Flask properly
instead of this
from flask import request
use this
from flask import Flask, request
This should work fine...

pymongo.errors.OperationFailure: Authentication failed. I need to save files from html forms

This error arises when I try to run the code below. It works fine when I remove mongo.save command. Anyway the text data is still getting saved in the database. I need to store images too. How to do that?
Python Code:
from flask import Flask, render_template, request, redirect, url_for
import pymongo
from pymongo import MongoClient
from flask_pymongo import PyMongo
app = Flask(__name__)
# configuration
app.config["MONGO_URI"] = "mongodb://Aayushi:Aayushi4799#localhost:27017/Test_Db"
app.config["DB_NAME"] = "Test_Db"
app.config["SECRET_KEY"] = "Aayushi4799"
print("configured")
# connect to mongodb
mongo1 = PyMongo(app)
db = mongo1.db
col = mongo1.db["Test_Db"]
print("connected")
# create new database
my_client = pymongo.MongoClient("mongodb://localhost:27017/")
my_db = my_client["Test_Db"]
print(my_client.list_database_names())
#connect to collections
my_col = my_db["Test_Col"]
#app.route('/')
def home():
return render_template("forms.html")
#app.route('/view', methods=['POST'])
def view():
form_details = {'name': request.form["name"], 'email': request.form["email"], 'pass': request.form["pass"]}
form_img = request.files["file"]
x = my_col.insert_one(form_details)
y = mongo1.save_file(form_img.filename, form_img)
if x and y:
return redirect(url_for("thank_you"))
else:
return "Try Again"
#app.route('/thankyou')
def thank_you():
return render_template("thankyou.html")
if __name__ == '__main__':
app.run(host='192.168.1.7', port=int(5000), debug=True)
I discovered the answer to my above question myself so I'm sharing it here for anyone who might face the same issue.
Follow the link provided and I think you'll be good to go.
https://pythonise.com/series/learning-flask/flask-uploading-files

Flask-pymongo RuntimeError: Working outside of application context

I'm writing a program to read mongodb document based on id field using flask-pymongo. But I'm getting error, can anybody tell me where am I going wrong?
code:
from flask import Flask, make_response, jsonify
from flask_pymongo import PyMongo
from collections import OrderedDict
from bson import json_util
import json
app = Flask('__name__')
app.config['MONGO_DBNAME'] = 'db_name'
app.config['MONGO_URI'] = 'mongodb://192.168.55.24:27017/db_name'
mongo_connection = PyMongo(app)
#app.route('/')
def index(inp_id):
collection = mongo_connection.db.table_name
one_record = collection.find_one({'id': inp_id})
obj_str = json_util.dumps(one_record)
obj_dict = json.loads(obj_str, object_hook=OrderedDict)
return make_response(jsonify(obj_dict), 200)
if __name__ == '__main__':
index('5cd00a468b36db516b6d2f16') # I think this is where I'm going wrong
giving me the below error:
RuntimeError: Working outside of application context.
If I pass id value directly in the place of inp_id I get the result but I'm trying to write a generic one.
Flask has an application context, You might need to use app.app_context() to make it work.
The application context keeps track of the application-level data
during a request, CLI command, or other activity. Rather than passing
the application around to each function, the current_app and g proxies
are accessed instead.
Try this :
def index(inp_id):
with app.app_context():
collection = mongo_connection.db.table_name
one_record = collection.find_one({'id': inp_id})
obj_str = json_util.dumps(one_record)
obj_dict = json.loads(obj_str, object_hook=OrderedDict)
return make_response(jsonify(obj_dict), 200)
For more information, read Flask Application context

flask context inside context , for jsonfy, all in a single page

I'm having a single test for retrieve documents in a single page, i know it's not correct to do in a single page; but it's just to understand all this work like pure script, not for an api restful.
My problem is when i use:
print (jsonify({'result' : output}))
i've get this error:
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
when I replace this line by
print ( output)
have no erros and have the documents.
How i can to specify a context for jsonify ? inside another context ? because i'm already using
with app.app_context():
Here the code:
from flask import Flask
from flask import g
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
from flask import make_response
from bson.objectid import ObjectId
from flask import current_app
import sys
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'restdb'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/crm1'
#app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error':'Notfound' }),404)
with app.app_context():
mongo = PyMongo(app)
star = mongo.db.accounts
output = []
for s in star.find():
output.append({'id': str(s['_id']) ,'firstname' : s['firstname'], 'lastname' : s['lastname']})
print (jsonify({'result' : output}))
#print ( output)
if __name__ == '__main__':
app.run(debug=True)
Jsonify Works with HttpResponse.
You can use python json module and print the output
Like:
import json
print(json.dumps(output))

Sqlalchemy and Flask API won't return column and value from a database

I'm running a flask web framework tied in to a sqlite databade. I'm having an issue returning a query that includes both the column name and the value of that column. I'm including the relevant code below.
import threading
import time
import KeySys
import serial
from flask import Flask, request
from flask_restful import reqparse, abort, Api, Resource
from sqlalchemy import create_engine
from json import dumps
from time import sleep
from datetime import datetime
e = create_engine('sqlite:///lockdb.db')
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('LockSwitch')
class Keystat_Meta(Resource):
def get(self):
#Connect to databse
conn = e.connect()
#Perform query and return JSON data
query = conn.execute('select * from LockStat')
return {'KeyStat': [query.cursor.fetchall()]} # I've tried keys() all() items(column, value) and various different queries.
api.add_resource(Keystat_Meta, '/keystat')
if __name__ == '__main__':
app.run()
If anyone else is struggling with this, it took me a day of pounding at it but I found a solution
return {'KeyStat': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}

Categories