Display MongoDB Documents data on a Webpage using Python Flask - python

I wrote a code using Python and trying to display all the Documents from Mongodb on a web page. However, on webpage I see the Column names, but no data.
And on the command, it does print all the data. Any help is greatly appreciated.
import pymongo
from pymongo import MongoClient
import datetime
import sys
from flask import Flask, render_template, request
import werkzeug
from flask_table import Table,Col
from bson.json_util import dumps
import json
app = Flask(__name__)
try:
client = pymongo.MongoClient("XXXX")
print("Connected to Avengers MongoClient Successfully from Project
Script!!!")
except:
print("Connection to MongoClient Failed!!!")
db = client.avengers_hack_db
#app.route('/')
def Results():
try:
Project_List_Col = db.ppm_master_db_collection.find()#.limit(10)
for row in Project_List_Col:
print(row)
return render_template('Results.html',tasks=row)
except Exception as e:
return dumps({'error': str(e)})
if __name__ == '__main__':
app.run(debug = True)
The HTML (Results.html) Page is:
<html>
<body>
{% for task_id in tasks %}
<h3>{{task_id}}</h3>
{% endfor %}
</body>
</html>

Removed the for loop and rewrote the code as below:
#app.route('/')
def Results():
try:
Project_List_Col = db.ppm_master_db_collection.find()
return render_template('Results.html',tasks=Project_List_Col)
except Exception as e:
return dumps({'error': str(e)})
if __name__ == '__main__':
app.run(debug = True)
Documents are displayed on the HTML Page as is.
(***Will work on the formatting part. Meanwhile any pointers are greatly appreciated.)

Try using key,value function of for loop and also remove that loop in the python app file from route like upper answer #Dinakar suggested

Related

Python Code on my XAMPP Website won´t work

from flask import Flask, render_template, request
import random
import datetime
app = Flask(__name__)
# List to store the submitted URLs
urls = []
#app.route('/')
def index():
return render_template('index.html')
#app.route('/submit', methods=['POST'])
def submit():
url = request.form['url']
# Add the URL to the list and return a success message
urls.append(url)
return "URL submitted successfully!"
#app.route('/stream')
def stream():
# Select a random URL from the last 20 days
now = datetime.datetime.now()
twenty_days_ago = now - datetime.timedelta(days=20)
recent_urls = [url for url in urls if url.submission_time > twenty_days_ago]
current_song_url = random.choice(recent_urls)
return render_template('stream.html', url=current_song_url)
if __name__ == '__main__':
app.run(debug=True)
I want to use this Code for my XAMPP Website (Html/php mostly used) but it only shows the code. So I watched some tutorials with config stuff and all that but then there is an internal server error. What should I do?
I tried to config Apache (httpd.conf) and installed everything (Python, Flask etc.)

AttributeError: 'str' object has no attribute 'client'

I have a code where, I am establishing connection with MongoDB. This code is
ConnectMongoDB.py:
import pymongo
from pymongo import MongoClient
from flask import Flask, render_template, request,redirect,url_for
app = Flask(__name__)
# Connection to MongoDB
class ConnectMdb:
#staticmethod
def connect2mongodb():
global client
try:
client = pymongo.MongoClient("mongodb") # modified to avoid showing actual string. Kindly ignore this part.
print("Connected to Avengers MongoClient Successfully!!!")
print (type(client))
print(client)
except:
print("Connection to MongoClient Failed!!!")
#db = client.avengers_hack_db
return("Connection established")
if __name__ == '__main__':
ConnectMdb.connect2mongodb()
I import this script in another program which has some business logic. Here is some part of the code which is relevant to this issue:
ProcessData.py:
import pymongo
from pymongo import MongoClient
import datetime
import sys
from flask import Flask, render_template, request
#import ProcessTaskData
#import werkzeug
import ConnectMongoDB as cDB
app = Flask(__name__)
CMdb = cDB.ConnectMdb.connect2mongodb()
db = CMdb.client.avengers_hack_db
#app.route('/')
def index():
return render_template('index.html')
#app.route('/Avengers',methods = ['POST'])
def Avengers():
ip = request.remote_addr
Project_ID = request.form['pid']
Name = request.form['pname']
Resource_Names = request.form['rsrc']
db.ppm_master_db_collection.insert_many([
{"Org_Id":"",
"Name": Name,
"last_modified": datetime.datetime.utcnow()}
])
return render_template('ptasks.html', user_ip=ip)
#app.route('/ProjectTasks',methods = ['POST'])
def ProjectTask():
ip = request.remote_addr
Task_ID = request.form['tid']
TAlert = request.form['talrt']
TResource_Names = request.form['trsrc']
db.ppm_tasks_data_collection.insert_many([
{"Task_ID": Task_ID,
"Resource_Names": TResource_Names,
"last_modified": datetime.datetime.utcnow()}
])
return render_template('ptasks.html', user_ip=ip)
if __name__ == '__main__':
app.run(debug = True)
If I put the code from ConnectMongoDB.py directly in the ProcessData.py rather than importing, it works good. But from separate file it errors.
Also, client is of type:
<class 'pymongo.mongo_client.MongoClient'>
Ideally it is expected to behave normally (establish connection to db as well) like when the code is in the ProcessData.py. Not sure where am I missing.
Changing
db = CMdb.client.avengers_hack_db
to
db = cDB.client.avengers_hack_db
should make your error go away, you are referencing the wrong thing. The return value of your staticmethod is a string, and it has no client attribute.
A bit better approach would be if your connect2mongodb method would return client:
class ConnectMdb:
#staticmethod
def connect2mongodb():
try:
client = pymongo.MongoClient("mongodb") # modified to avoid showing actual string. Kindly ignore this part.
print("Connected to Avengers MongoClient Successfully!!!")
print (type(client))
print(client)
except:
raise Exception("Connection to MongoClient Failed!!!")
return client
This way db = CMdb.client.avengers_hack_db would work.

How to send and receive data from flask?

I am trying to send a python dictionary created from client.py to my webservice, have the webservice do something to the data, and return a boolean to client.py. This is the code I have so far for the server and client:
Server side (inside webservice.py):
from flask import Flask
from flask import request
import json
app = Flask(__name__)
#app.route('/determine_escalation',methods = ['POST'])
def determine_escalation():
jsondata = request.form['jsondata']
data = json.loads(jsondata)
#stuff happens here that involves data to obtain a result
result = {'escalate':'True'}
return json.dumps(result)
if __name__ == '__main__':
app.run(debug=True)
Client side (inside client.py):
import sys
import json
import requests
conv = [{'input': 'hi', 'topic': 'Greeting'}]
s = json.dumps(conv)
res = requests.post("http://127.0.0.1:5000/determine_escalation",data=s)
print res.text
But when I print out res.text, I get this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
What am I doing wrong, and how can I fix this? New to Flask and JSON stuff so any help is appreciated.
OK - a few issues here:
First, you can use requests.get_json() to retrieve your JSON data at the server end:
from flask import Flask
from flask import request
import json
app = Flask(__name__)
#app.route('/determine_escalation/', methods = ['POST'])
def determine_escalation():
jsondata = request.get_json()
data = json.loads(jsondata)
#stuff happens here that involves data to obtain a result
result = {'escalate': True}
return json.dumps(result)
if __name__ == '__main__':
app.run(debug=True)
Also, when you are putting your data together, rather than using "data=s" to send the request, use "json=s":
import sys
import json
import requests
conv = [{'input': 'hi', 'topic': 'Greeting'}]
s = json.dumps(conv)
res = requests.post("http://127.0.0.1:5000/determine_escalation/", json=s).json()
print(res['escalate'])
Please note that I have added trailing slashes at the end of the URL - this is just good practice :-)
I've also incorporated MarcelK's suggested changes - removing the quotes from the boolean 'True' (server side) and using .json() to parse the response on the client side - both of these are great suggestions.
I've tested this revised version (and re-revised version) and it works fine.

Extracting image then thumbnail that image and display on index.html

So I made my mind to use python goose for extracting the main image when url is inserted. I found good example here https://blog.openshift.com/day-16-goose-extractor-an-article-extractor-that-just-works/ the blog example is using flask, I tried to make the script for people using django
Here is my media.py ( not sure if this works yet )
media.py
import json
from goose import Goose
def extract(request):
url = request.args.get('url')
g = Goose()
article = g.extract(url=url)
resposne = {'image':article.top_image.src}
return json.dumps(resposne)
How do I use the image I get from above and put it in a thumbnail and display that on the index.html ? please, any help would be very appreciated. Merry Christmas
Edit 1 : I tried to convert below to django script but in my case only script image
from flask import Flask
from flask import jsonify
from flask import render_template
from flask import request
from goose import Goose
app = Flask(__name__)
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/api/v1/extract')
def extract():
url = request.args.get('url')
g = Goose()
article = g.extract(url=url)
response = {'title' : article.title , 'text' : article.cleaned_text[:250], 'image': article.top_image.src}
return jsonify(response)
if __name__ == "__main__":
app.run(debug=True)

Displaying stackOverflow API JSON data using Flask

I've been trying to display my username and reputation from the JSON data retrieved from the StackOverflow API.
Im using the python module Requests to retrieve the data.
Here is the code
from flask import Flask,jsonify
import requests
import simplejson
import json
app = Flask(__name__)
#app.route("/")
def home():
uri = "https://api.stackexchange.com/2.0/users? order=desc&sort=reputation&inname=fuchida&site=stackoverflow"
try:
uResponse = requests.get(uri)
except requests.ConnectionError:
return "Connection Error"
Jresponse = uResponse.text
return Jresponse
if __name__ == "__main__":
app.run(debug = True)
The unused imports is what I need to get this done but cant seem to know how to get it done.
Below is what is returned to the browser, I want to just display the username [display_name] and the reputation. what options do I have to get this done ?
{"items":[{"user_id":540028,"user_type":"registered","creation_date":1292207782,"display_name":"Fuchida","profile_image":"http://www.gravatar.com/avatar/6842025a595825e2de75dfc3058f0bee?d=identicon&r=PG","reputation":13,"reputation_change_day":0,"reputation_change_week":0,"reputation_change_month":0,"reputation_change_quarter":0,"reputation_change_year":0,"age":24,"last_access_date":1332905685,"last_modified_date":1332302766,"is_employee":false,"link":"http://stackoverflow.com/users/540028/fuchida","website_url":"http://blog.Fuchida.me","location":"Minneapolis
MN","account_id":258084,"badge_counts":{"gold":0,"silver":0,"bronze":3}}],"quota_remaining":282,"quota_max":300,"has_more":false}
Use json.loads() to read and decode the data.
from flask import Flask,jsonify
import requests
import simplejson
import json
app = Flask(__name__)
#app.route("/")
def home():
uri = "https://api.stackexchange.com/2.0/users? order=desc&sort=reputation&inname=fuchida&site=stackoverflow"
try:
uResponse = requests.get(uri)
except requests.ConnectionError:
return "Connection Error"
Jresponse = uResponse.text
data = json.loads(Jresponse)
displayName = data['items'][0]['display_name']# <-- The display name
reputation = data['items'][0]['reputation']# <-- The reputation
return Jresponse
if __name__ == "__main__":
app.run(debug = True)

Categories

Resources