Python3 Flask: "Function() missing 1 required positional argument: 'test_output'" - python-3.x

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.

Related

How Can i pass url as a Vairable in Flask route

I want to pass a youtube link as a route parameter but it gives me an error
app = Flask(__name__)
#app.route('/')
def test():
return 'Hello'
#app.route("/<path:url>")
# a youtube link would be passed here
def get_data(url):
result = scrap(url)
# do something with that url
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True )
here i need a youtube link as a variable but the path:url does not give me full path so i cant use that link, is there a way so that i cant retrieve the full path?
As it's a URL you're parsing, it might be better to parse it as a query parameter rather than a route parameter, this way it wouldn't be as easy for it to get mangled by the parser.
URL Query parameters can be extracted in flask using request.args.get
So your program would look something like this,
app = Flask(__name__)
#app.route('/')
def test():
return 'Hello'
#app.route("/video")
def get_video_data():
url = request.args.get("url")
result = scrape(url)
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True)
Then you can pass the URL using http://localhost:8080/video?url=youtubeurl_here

Python If-Condition with While-True Infinite Loop Conflict

I want to ask, right now I’m doing the python3 http web server. However it has the issue on “if-condition” when it stuck at “while-true”. When I want to use other “if condition”, the program stuck at “while-true” and cannot proceed other program.
from http.server import BaseHTTPRequestHandler, HTTPServer
import subprocess
Request = None
class RequestHandler_httpd(BaseHTTPRequestHandler):
def do_GET(self):
global Request
messagetosend = bytes('Hello Worldddd!',"utf")
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', len(messagetosend))
self.end_headers()
self.wfile.write(messagetosend)
Request = self.requestline
Request = Request[5 : int(len(Request)-9)]
print(Request)
if Request == 'onAuto':
def always_run():
subprocess.run("python3 satu.py ;", shell=True)
subprocess.run("python3 dua.py ;", shell=True)
while True:
always_run() #the program stuck here and other if cannot be used
if Request == 'onFM':
subprocess.run("python3 satu.py ;", shell=True)
if Request == 'onQR':
subprocess.run("python3 dua.py ;", shell=True)
if Request == 'offSYS':
subprocess.run("python3 OFF_SYSTEM.py ;", shell=True)
return
server_address_httpd = ('X.X.X.X',8080) #my private address
httpd = HTTPServer(server_address_httpd, RequestHandler_httpd)
print('Starting Server')
httpd.serve_forever()
As JonSG commented. Your
while True:
always_run()
is blocking the further execution of your code. So you have to run it in a separate thread:
import threading
class AlwaysThread(threading.Thread):
def __init__(self):
super(AlwaysThread, self).__init__()
self.stopThread = False
def run(self):
self.stopThread = False
while not self.stopThread:
always_run()
# where you previously have done the endless loop
t = AlwaysThread()
t.start()
# stop it with t.stopThread = True
I would also use a switch statement instead of the if cascade.

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})

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.

how to implement a nested route in flask that each do different things

#app.route('/sera/<mount_type>')
#app.route('/sera', methods=['POST'])
def return_pages():
if request.method == 'POST':
usin = request.form.get('serval')
global mount_type
mount_type = usin
#this section runs independend of the search box
if mount_type == 'acongagua':
return render_template('result.html',aa=acongagua.names, ac=acongagua.location, ad=acongagua.metre_height, ae=acongagua.feet_height)
elif mount_type == 'adams':
return render_template('result.html',aa=adams.names, ac=adams.location, ad=adams.metre_height, ae=adams.feet_height)
else:
return 'YOU HAVE ENTERED AN INCORRECT VALUE'
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
that is the python flask code i'm trying to run the first if statement should run when the form is filled and should have its values passed to the seconf if statement
You can use redirect to redirect the request, and pass the value as URL paramater:
from flask import redirect
#app.route('/sera/<mount_type>')
#app.route('/sera', methods=['POST'])
def return_pages():
if request.method == 'POST':
usin = request.form.get('serval')
return redirect(url_for('return_pages', mount_type=usin)) # <--
...

Resources