ValueError: Must be a coordinate pair or Point - python-3.x

i want to pass my latitude and langitude values to my flask route but everytime i am getting this error: ValueError: Must be a coordinate pair or Point
however i have tried this and its working fine:
from flask import Flask, render_template
from geopy.geocoders import Nominatim
app = Flask(__name__)
geolocator = Nominatim()
#app.route('/location')
def lang_and_lat():
location = geolocator.reverse("21.0943, 81.0337")
address = location.address
return render_template('ip.html', address=address)
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask, render_template
from geopy.geocoders import Nominatim
app = Flask(__name__)
geolocator = Nominatim()
#app.route('/location/<lat>/<lang>')
def lang_and_lat(lat, lang):
location = geolocator.reverse(lat, lang)
address = location.address
return render_template('ip.html', address=address)
if __name__ == '__main__':
app.run(debug=True)

you need to do
location = geolocator.reverse(f'{lat}, {lang}')
or
location = geolocator.reverse(Point(lat, lang))
in second case you need to from geopy.point import Point

Related

Not found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again

I have written a small deep learning method to practice deplyoing with a Flask application. It's a simple application that just needs to distinguish a cat from a fish.
Here is the short code:
from io import BytesIO
import requests
import torch
from flask import Flask, jsonify, request
from PIL import Image
from torchvision import transforms
from catfish_model import catfish_classes, catfish_model
def load_model():
m = catfish_model
m.eval()
return m
load_model()
img_transforms = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
def create_app():
app = Flask(__name__)
#app.route("/")
def status():
return jsonify({"status": "ok"})
#app.route("/predict", methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
img_url = request.form.image_url
else:
img_url = request.args.get('image_url', '')
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
img_tensor = img_transforms(img).unsqueeze(0)
prediction = model(img_tensor)
predicted_class = CatfishClasses[torch.argmax(prediction)]
return jsonify({"image": img_url, "prediction": predicted_class})
return app
def main():
app = create_app()
app.run(debug=True)
if __name__ == "__main__":
main()
This is how I launch the Flask app:
set FLASK_APP=catfish_server.py
flask run --port=8080
Then i am starting the browser an give the follow command to predict if the pic on an webside is a cat or a fish:
127.0.0.1:8080/predict image_url=https://www.augsburger-allgemeine.de/img/bilder/crop55113376/4006562429-cv16_9-w1880/Bailey-aus-Gundelfingen.jpg
now I get the error message:
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I don't understand exactly why.
I don't think a space in the URL makes sense. I think you should put a ?.
127.0.0.1:8080/predict?image_url=https://www.augsburger-allgemeine.de/img/bilder/crop55113376/4006562429-cv16_9-w1880/Bailey-aus-Gundelfingen.jpg
However in flask you can do this:
#app.route("/predict/<img_url>", methods=['GET', 'POST'])
def predict(img_url):
img = Image.open(BytesIO(response.content))
img_tensor = img_transforms(img).unsqueeze(0)
prediction = model(img_tensor)
predicted_class = CatfishClasses[torch.argmax(prediction)]
return jsonify({"image": img_url, "prediction": predicted_class})

cannot import name python 3.10

Hi I have created a main page with python with the code of:
from website import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
Second file with the code of:
from flask import Flask
def create_app():
app = Flask(__name__)
app.config['SECRET_kEY'] = 'computer1'
return app
I have enter from website import 'create app' and I am getting an error message which states
cannot import name 'createapp'
python\python 310\lib\site.package\website__init__py
When I press run the above comes up. Can someone please advise?

How to use the value obtained in POST method outside the function

Below is my directory structure:
/home
|___ /sub_directory
|__abc.py
|__ xyz.py
Below is my xyz.py code:
from flask import Flask, request, redirect, url_for,send_from_directory, jsonify, render_template
import mysql.connector
from mysql.connector import Error
app = Flask(__name__)
try:
connection = mysql.connector.connect(host='127.0.0.1',database='test',user='root',password='')
if connection.is_connected():
db_Info = connection.get_server_info()
cursor = connection.cursor()
cursor.execute("select id,name from skill_category;")
record = cursor.fetchall()
out = [item for t in record for item in t]
except Error as e:
print("Error while connecting to MySQL",e)
#app.route('/', methods=['GET'])
def dropdown():
val = record
return render_template('Rankcv.html', val = val)
#app.route('/get-subskills', methods=['POST'])
def get_subskills():
skills = request.form['select_skills']
cursor.execute("SELECT skill_items.name FROM skill_items WHERE skill_items.category_id = " + skills + " ;")
record = cursor.fetchall()
out = [item for t in record for item in t]
...........
...........
...........
return jsonify(something)
if __name__ == "__main__":
app.run(debug=True)
Now I have to use the value of variable out and skills in abc.py.
I tried importing xyz directly and tried to retrieve the value using function name (get_subskills), but it didnt work. Can someone please explain how to solve this?
Import the abc function into xyz.

flask server unresponsive after second load

After I implemented caching on my flask server, everything works perfectly on local host. First execution is 8000ms, second is 26ms, therefore its working.
When I deployed the application on the AWS ec2 box, the first execution is 21000ms and whenever I try to run it again, it comes with server not responsive.
This is the code:
#!flask/bin/python
from flask_cache import Cache
from flask import Flask, jsonify
from flask import request
from flask_caching import Cache
import json
import nltk, string
import operator
from sklearn.feature_extraction.text import TfidfVectorizer
import re
import time
import access_json
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
with open('JSON files/thesaurus.json', 'r') as fp:
thesaurus_dict = json.load(fp)
with open('JSON files/JOBS.json', 'r') as f:
json_list = json.load(f)
def output(word_list):
return filter_toplist
#app.route('/postjson', methods=['POST'])
#cache.cached(timeout=20)
def json_handler():
content = request.get_json(force=True)
word_list = access_json.read_parsed_JSON(content)
return jsonify ({'jobs': output(word_list)})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
This is not all of the code but the one relevant to the flask server.

Python is throwing "syntax error" while using #app.route

Python is throwing "Syntax Error" when I compile the code below.
File "app.py", line 11
#app.route('/')
^
SyntaxError: invalid syntax
I'm not sure what it means.
from flask import Flask, render_template
import urllib.request
import json
import time
app = Flask(__name__ ,template_folder='template')
namep = "PewDiePie"
namet = "TSeries"
key = "MY_API_KEY"
#app.route("/")
for x in range(5):
time.sleep(2)
datat = urllib.request.urlopen("https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername="+namep+"&key="+key).read()
datap = urllib.request.urlopen("https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername="+namet+"&key="+key).read()
subt = json.loads(datat)["items"][0]["statistics"]["subscriberCount"]
subsp = json.loads(datap)["items"][0]["statistics"]["subscriberCount"]
def main():
return render_template('index.html', pewds_sub = subsp, tseries_sub = subt)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=80)
Any help regarding this is appreciated.
Thanks!
You must define the function after the route decorator, i.e. after #app.route
Updated code
#app.route("/")
def function_main():
#all logics here
return render_template('index.html', pewds_sub = subsp, tseries_sub = subt)
Make sure to process your calculations inside function else try to pass those argument in defined function.
from flask import Flask, render_template
import urllib.request
import json
import time
app = Flask(__name__ ,template_folder='template')
namep = "PewDiePie"
namet = "TSeries"
key = "MY_API_KEY"
#app.route("/")
def main():
for x in range(5):
time.sleep(2)
datat = urllib.request.urlopen("https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername="+namep+"&key="+key).read()
datap = urllib.request.urlopen("https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername="+namet+"&key="+key).read()
subt = json.loads(datat)["items"][0]["statistics"]["subscriberCount"]
subsp = json.loads(datap)["items"][0]["statistics"]["subscriberCount"]
return render_template('index.html', pewds_sub = subsp, tseries_sub = subt)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=80)
in my case,
I initiated a try block just above for the database connection and forget to put catch block, that's why I have encountered this error.
so I suggest anyone facing the same error,
should check the code above #app.route('/') because if you have import flask
properly this should work pretty fine syntax error in this statement usually indicates that you might have a problem above this line and not at that line.

Resources