I'm trying to create new lines using python for the variable "profile" using the 'new_line' variable, but I haven't been successful.
The code below does not produce errors. It gives me all 3 strings in one line and I'd like to get 3 lines.
I would like the output to look like this with a new line for each string.
response: response
Lat/Lon: 1293.2312,123123.432
City: New York"
from flask import Flask
from flask import jsonify
import requests
import json
import os
app = Flask(__name__)
#app.route('/change/')
def he():
API_KEY = "API_KEY"
CITY_NAME = "oakland"
url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&appid={API_KEY}"
response = requests.get(url).json()
new_line='\n'
profile = (
f"response: {response} ============== {new_line}"
f"Lat/Lon: {response['coord']} ========={new_line}"
f"City: {CITY_NAME}========{new_line}"
)
return profile
Try new_line='</br>'.
If you're viewing it in browser, it may interpret the page as badly formatted HTML and ignore line breaks and whitespaces, therefore you will need to use tags for that.
Related
I am trying to query the main image of the Wikipedia page for the Prime Minister of the UK: https://en.wikipedia.org/wiki/Prime_Minister_of_the_United_Kingdom
I got this method from various posts on StackOverflow. The problem is, for the PM's page, it returns the first image on the right-hand side of the page which is the Royal Coat of Arms. But when I query the page for the Home Secretary in the same way, it correctly returns the second image which is the portrait of the incumbent Home Sec Suella Braverman. You can see for yourself if you swap out pmPageID with HomeSecPageID in this line: result = getQuery(query.format(pmPageID))
Here is my code:
import requests
# import re
from flask import Flask
from flask_cors import CORS, cross_origin
from flask import jsonify
# from bs4 import BeautifulSoup
# from flask import Flask, render_template
# from urllib.request import urlopen
app = Flask(__name__)
cors = CORS(app)
def getQuery(search):
response = requests.get(search)
results = response.json()
return jsonify(results)
pmPageID = 24150
HomeSecPageID = 149104
query = 'https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=original&pageids={}'
#app.route('/')
#cross_origin()
def index():
result = getQuery(query.format(pmPageID))
return result
My question is, is there anything else I can do to pull the image of the incumbent prime minister?
The example use of pageimages in the documentation only returns one result, despite the target article containing more images and adding &pilimit=10 makes no difference (it should default to 50).
You can access all the images in that article using images instead e.g. https://en.wikipedia.org/w/api.php?action=query&prop=images&format=json&titles=Prime_Minister_of_the_United_Kingdom&imlimit=100&imdir=descending but for some reason, that returns the images in a random order compared to how you see them in the article. The one you're after is ninth in that list, but if edits are made to the article, that could change.
I have a function calculate_full_eva_web(input:dict) it receives input dictionary several function applied on this input to create calculations dict, after calculations i want to send this data to html dashboard and after send data to html file i can play there with jinja stuff. i am unable to do so, i tried several ways but flask throws error. and also i don't know much about ajax ,may be ajax will do my work, let me know. that is why i am tagging ajax people on this post. Traceback is also attached..Thank you
In simple words, i want to send data to html in flask ! Please check my code. Let me know if i am doing anything wrong.
imports ...
from other file import other_functions
from other file import other_functions_2
from other file import other_functions_3
app = Flask(__name__, template_folder='templates/')
#app.route("/dashboard")
def calculate_full_eva_web(input:dict):
calculate_gap = other_functions(input)
calculate_matrix = other_functions_2(input)
average = other_functions_3(input)
data = dict{'calculate_gap':calculate_gap, 'calculate_matrix':calculate_matrix,'average':average}
return render_template('pages/dashboard.html', data = data)
if __name__ == "__main__":
app.run(debug=True)
The route receive a dict as input so you must change #app.route("/dashboard") to #app.route("/dashboard/<input>") and pass input to the route in the link of the route.
For example, I have a route as below.
#app.route('/user/<name>')
def user(name):
return render_template('home.html', name=name)
To pass name to the route, I access the link http://localhost:5000/user/myname.
I am trying to use DocumentConversionV1 function of watson_developer_cloud API on python , However the response in my case comes only as "<"Response 200">".
import sys
import os as o
import json
import codecs
from watson_developer_cloud import DocumentConversionV1
document_conversion = DocumentConversionV1(
username="873512ac-dcf7-4365-a01d-7dec438d5720",
password="bvhXbdaHtYgw",
version='2016-02-10',
url= "https://gateway.watsonplatform.net/document-conversion/api",
)
config = {
'conversion_target': 'NORMALIZED_TEXT',
}
i = "v.docx"
with open((i),'rb') as doc:
res = document_conversion.convert_document(document = doc , config = config)
print(res)
First and foremost, delete your service credentials and recreate them through Bluemix. (Posting them on a public forum is usually a bad idea.) ;o)
Now, to actually answer the question... You want to get the content of the response. Right now, you're printing the response itself. Try
print(res.content)
See https://github.com/watson-developer-cloud/python-sdk/blob/master/examples/document_conversion_v1.py#L16
I'm building a bottle.py app that grabs some data from MongoDB and renders it into a web page using pygal.
The code produces a Error: 500 Internal Server Error in my browser.
On the server, I see: Exception: TypeError('serve_static() takes exactly 1 argument (0 given)',).
My question: how do I correct the code to render the .svg file?
The code:
import sys
import bottle
from bottle import get, post, request, route, run, static_file
import pymongo
import json
import pygal
connection = pymongo.MongoClient("mongodb://localhost", safe=True)
#get('/chart')
def serve_static(chart):
db = connection.control
chart = db.chart
cursor = chart.find({}, {"num":1, "x":1, "_id":0})
data = []
for doc in cursor:
data.append(doc)
list = [int(i.get('x')) for i in data]
line = pygal.Line()
line.title = 'widget quality'
line.x_labels = map(str, range(1, 20))
line.add('quality measure', list)
line.render_to_file('chart.svg')
try:
return static_file(chart.svg, root='/home/johnk/Desktop/chart/',mimetype='image/svg+xml')
except:
return "<p>Yikes! Somethin' wrong!</p>"
bottle.debug(True)
bottle.run(host='localhost', port=8080)
You didn't give a parameter to the route, so the function doesn't get any.
What you probably want to do, is either:
#get('/<chart>')
def serve_static(chart):
...
If you want /myfile.svg to work, or:
#get('/chart/<chart>')
def serve_static(chart):
...
If you want /chart/myfile.svg to work.
If you just want to show the same SVG file every time, you can just leave off the parameter:
#get('/chart')
def serve_static():
...
I am a beginner in python to pull some data from reddit.com
More precisely, I am trying to send a request to http:www.reddit.com/r/nba/.json to get the JSON content of the page and then parse it for entries about a specific team or player.
To automate the data gathering, I am requesting the page like this:
import urllib2
FH = urllib2.urlopen("http://www.reddit.com/r/nba/.json")
rnba = FH.readlines()
rnba = str(rnba[0])
FH.close()
I am also pulling the content like this on a copy of the script, just to be sure:
FH = requests.get("http://www.reddit.com/r/nba/.json",timeout=10)
rnba_json = FH.json()
FH.close()
However, I am not getting the full data that is presented when I manually go to
http://www.reddit.com/r/nba/.json with either method, in particular when I call
print len(rnba_json['data']['children']) # prints 20-something child stories
but when I do the same loading the copy-pasted JSON string like this:
import json
import urllib2
fh = r"""{"kind": "Listing", "data": {"modhash": ..."""# long JSON string
r_nba = json.loads(fh) #loads the json string from the site into json object
print len(r_nba['data']['children']) #prints upwards of 100 stories
I get more story links. I know about the timeout parameter but providing it did not resolve anything.
What am I doing wrong or what can I do to get all the content presented when I pull the page in the browser?
To get the max allowed, you'd use the API like: http://www.reddit.com/r/nba/.json?limit=100