Python is throwing "syntax error" while using #app.route - python-3.x

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.

Related

sunrpc implementation in python

I wanted to create sunrpc client in python using xdrlib library and sunrpc server is already implemented in C. I have implemented one rpc client in python over udp by referencing following link:
https://svn.python.org/projects/stackless/trunk/Demo/rpc/rpc.py
It is giving timeout error as well as can not unpack none object error.
can anyone guide me on this how it can be done?
there is no information available on this on google.
has anyone implemented such type of code?
please help..I am struggling on this like a week now.
Here is my client code:
import rpc
import rpc_new
from tq_const import *
from tq_type import *
import tq_pack
import socket
import os
class PartialTQClient:
def __init__(self):
pass
def addpackers(self):
self.packer = tq_pack.TQPacker(self)
self.unpacker = tq_pack.TQUnpacker(self, '')
def unpack_month_temperatures(self):
return self.unpacker.unpack_array(self.unpacker.unpack_uint)
def call(self, month):
res = self.make_call(0, month, self.packer.pack_uint, self.unpack_month_temperatures)
return res
class UDPTQClient(PartialTQClient, rpc.RawUDPClient):
def __init__(self, host):
rpc.RawUDPClient.__init__(self, host, TQ_PROGRAM, TQ_VERSION, TQ_PORT)
PartialTQClient.__init__(self)
if __name__ == "__main__":
tqcl = UDPTQClient("127.0.0.1")
print(tqcl)
res = tqcl.call(12)
#print ("Got result", res)
Here is my server code:
import rpc
import rpc_new
from tq_const import *
from tq_type import *
import tq_pack
import socket
import os
class TQServer(rpc.UDPServer):
print("Inside TQServer")
def handle_0(self):
print ("Got request")
m = self.unpacker.unpack_uint()
print ("Arguments was", m)
self.turn_around()
self.packer.pack_array([1, 2, 3], self.packer.pack_int)
#res = PFresults(self, status=TRUE, phone="555-12345")
#res.pack()
if __name__ == "__main__":
s = TQServer("", TQ_PROGRAM, TQ_VERSION, TQ_PORT)
print ("Service started...",s)
try:
print("Trying")
s.loop()
finally:
print ("Service interrupted.")
When I am running client and server on localhost I am getting following error: TypeError: cannot unpack non-iterable NoneType object

PokeAPI & Flask: Combining different properties on API

API beginner here,
I'm creating an API that calls both a character name and their description with one ENDPOINT. So far I have the data appearing at separate endpoints.
Goal: Getting output format ('http://127.0.0.1:5000/v1/pokemon/string:name') to look similar to this:
{ "name": "pichu", "description": "It is not yet skilled at storing electricity.It may send out a jolt if amused or startled."}
from flask import Flask, jsonify, Response
from flask_restful import Resource, Api, fields, marshal_with
import requests, json
app = Flask(__name__)
api = Api(app)
# Prints all Pokemon via JSON
#app.route('/v1/pokemon/all', methods=['GET'])
def poke_names():
data = []
name_url = "https://pokeapi.co/api/v2/pokemon?limit=151"
while True:
resp = requests.get(name_url)
json = resp.json()
data.extend(json.get('results', []))
name_url = json.get('next')
if not name_url: break
return jsonify(data)
#app.route('/v1/pokemon/<string:name>/title', methods=['GET'])
def get_poke(name):
return jsonify({'name': name})
#flavor Text ie pokemon description
#app.route('/v1/pokemon/<int:pokemon_id>', methods=['GET'])
def get_description(pokemon_id):
descrip_url = f"https://pokeapi.co/api/v2/pokemon-species/{pokemon_id}"
r = requests.get(descrip_url)
json_blob = r.json()
flav_text = extract_descriptive_text(json_blob)
return jsonify({'description': flav_text})
def extract_descriptive_text(json_blob, language='en'):
text = []
for f in json_blob['flavor_text_entries']:
if f['language']['name'] == language:
text.append(f['flavor_text'])
return text
#error occurs below
#app.route('/v1/pokemon/<string:name>')
def all_poke_data(name, flav_text):
return jsonify({'name':name, 'description':flav_text})
if __name__ == "__main__":
app.run(debug=True)
Error: When I try to combine them I get
TypeError: all_poke_data() missing 1 required positional argument: 'flav_text'
Thank you for any pointers provided!
Figured it out!
Just add this function, which is a combination of both route functions
#app.route('/v1/pokemon/<string:name>')
def get_poke(name):
descrip_url = f"https://pokeapi.co/api/v2/pokemon-species/{name}"
r = requests.get(descrip_url)
json_blob = r.json()
flav_text = extract_descriptive_text(json_blob)
return jsonify({'name': name},{'description': flav_text})

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.

ValueError: Must be a coordinate pair or Point

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

Python3 Flask: "Function() missing 1 required positional argument: 'test_output'"

I'm just starting with FLASK and stumbled upon this error:
test() missing 1 required positional argument: 'test_output'
Why is this happening? The functions is declared before calling it and usually this error means that the argument while calling the function is missing.
def foo(x):
print (x)
foo(x)
So this is working, why doesn't it work in my script with flask?
Here is my "full" code:
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo
app = Flask(__name__)
#app.config ['MONGO_DBNAME'] = 'DBfoo'
app.config['MONGO_URI'] = 'mongodb://127.0.0.1:27017/Test'
mongo = PyMongo(app)
#app.route('/TestRouteGet', methods=['GET', 'POST'])
def test(test_output):
print (test_output)
def get_Test():
collection = mongo.db.TestCol
if request.method == 'POST':
test_input = "Test BlaBla"
test(test_input)
if __name__ == '__main__':
app.run(debug=True)
When sending a POST request I should have the test_output ("Test Blabla") printed in the console.
Thanks for your time.
Your function expects test_output argument, you should get this argument from the url string http://flask.pocoo.org/docs/1.0/quickstart/#url-building
#app.route('/TestRouteGet/<test_output>', methods=['GET', 'POST'])
Then you can make a request to /TestRouteGet/insert_your_string and your function will print received string.

Resources