missing 1 required positional argument on Return - python

I'm getting missing 1 required positional argument on the code below. I tried different stuffs but no luck. I believe it is a small detail that I'm missing but since I'm a beginner on Python and I'm not being able to fix it myself.
import requests
from flask import Flask, jsonify, request, render_template
import os
app = Flask(__name__)
#app.route('/outages')
def map_status(data):
url = "https://my-api.local.com/data"
response = requests.get(url)
result_data = json.loads(response.text)
if(data['install_status']=='1'):
data['install_status']='Installed'
elif(data['install_status']=='3'):
data['install_status']='Maintenance'
return data
result_data['result']=map(map_status,result_data['result'])
return(list(result_data['result']))
This is the error I'm getting:
[ERR] TypeError: map_status() missing 1 required positional argument: 'data'
If I change the return for print, it works, but on this case I need to use return to get the data.

When you call a function that has arguments, you must specify the value of them.
The correct code would be:
result_data['result'] = map(map_status(insert_data), result_data['result'])
where (insert_data) is the place where you would insert the value of whatever needs to be put there.
If you don't want the argument to be required all the time you can specify an optional argument like so:
def map_status(data=None)
This makes the initial value of data a NoneType. When you want to call the function with the data argument, just do so like you would a normal argument, but with an equal sign, like so:
map_status(data="hello")
You can also just make the optional argument an empty literal:
def map_status(data="")

Related

unable to call a defined function, invalid syntax on a line i have used before in the code

#app.get("/drogaraia")
def scraperaia(urlbase="https://www.drogaraia.com.br/medicamentos",maximodepaginas=10):
listaprincipal= []
pagina=2
contador=1
while pagina<maximodepaginas:
testeurl= ((urlbase)+".html?p="+str(pagina))
page = requests.get(testeurl)
results= BeautifulSoup(page.content,"html.parser")
remedios = results.find_all("div",class_="container")
for remedio in remedios:
try:
link=(remedio.find("a", class_="show-hover"))['href']
preco=remedio.find(class_="price").getText().strip()
titulo=(remedio.find("a", class_="show-hover")).getText()
categoria=urlbase.rsplit('/',1)[-1]
listaremedio=[{'link':link,'preco':preco,'titulo':titulo,'categoria':categoria}]
listaprincipal.extend(listaremedio)
except:
pass
contador=contador+1
pagina=pagina+1
return(listaprincipal)
#app.get("/drogaraia/medicamentos/monitores-e-testes/teste-de-controle-glicemicos")
scraperaia(urlbase="https://www.drogaraia.com.br/medicamentos/monitores-e-testes/teste-de-controle-glicemicos",maximodepaginas=10)
Error message here:
scraperaia(urlbase="https://www.drogaraia.com.br/medicamentos/monitores-e-testes/teste-de-controle-glicemicos",maximodepaginas=10)
^^^^^^^^^^
SyntaxError: invalid syntax
I don't see how it can be wrong syntax. I have tried not assigning the variables inside the scraperaia() function, like so:
urlbase="https://www.drogaraia.com.br/medicamentos/monitores-e-testes/teste-de-controle-glicemicos"
maximodepaginas=10
scraperaia(urlbase,maximodepaginas)
and it still doesnt work.
The last two lines of your provided code are wrong. You need to use def to define a function.
You can define multiple routes bound to the same function. If you would like to know which route was used, you can use the Request object to get the request URL path (see documentation here and here). Working example below:
from fastapi import FastAPI, Request
app = FastAPI()
#app.get("/store")
#app.get("/store/monitors-and-tests")
def main(request: Request, baseurl: str = "https://someurl", maxpages: int = 10):
return {"Called from": request.url.path}

Generic Function Calls With Keyword Arguments

Working in Python 3.8.
I prefer to have one return per function as it makes debugging easier.
Current code which I can live with:
if foo:
return redirect(url_for('what.what'))
else:
return render_template('who.who', form=my_form)
Desired code though:
if foo:
ret_func = redirect
ref_func_args = url_for("what.what")
else:
ret_func = render_template
ret_func_args = ('who.html', form=my_form) # syntax help needed here
return ret_func(ret_func_args) # and probably some syntax help here also
Python understandably doesn't like the ret_func_args = ('who.html', form=my_form) and in particular form=my_form.
render_template is expecting a keyword argument named 'form'.
What is the proper syntax for ret_func_args = ('who.html', form=my_form) and perhaps the ret_func(ret_func_args) line? The ret_func(ret_func_args) does work if foo is true but can not figure out how to pass named parameters when foo is false in this case.

flask reqparse how to get empty list using action='append' (not by default)

i need to get empty list if it in request but also need to get None if argument don't given at all in request
if i defined argument like that
parser.add_argument('participating',type=int, nullable=False, action='append')
then if i do request like this
print(post('http://localhost:80/api/', json={'participating':[]}).json())
parser sees it like 'participating':None
and if i do that request
print(post('http://localhost:80/api/', json={}).json())
then parser also sees it like 'participating':None
i solved it by check for exist key in flask.request.json
if not args['participating'] and 'participating' in flask.request.json and not flask.request.json['participating']:
args['participating'] = flask.request.json['participating']
in that case values was:
args['participating'] = None
flask.request.json['participating'] = []
(but i open for any others solutions)

Python error - Can't redirect the url set up

I have code as follow. The app should be redirected to https://example.com?code={ cliient_id } but it failed with the error.
The error is:
redirect() takes 0 positional arguments but 1 was given
The code is below. Error is on the last line of extracted code.
client_id='XXXXXXXXXXXX'
#bp.route('/redirect', methods=['GET'])
def redirect():
authorize_url = f"https://example.com?code={ cliient_id }"
return redirect(authorize_url)
You are importing redirect from flask, but also defining your own function named redirect. Your new definition "wins", and your definition takes no arguments. Try naming your function redirect_ instead (or any other name), e.g.
client_id='XXXXXXXXXXXX'
#bp.route('/redirect', methods=['GET'])
def redirect_():
authorize_url = f"https://example.com?code={ cliient_id }"
return redirect(authorize_url)
Your function, as defined, takes zero arguments:
def redirect()
However, its return value is the redirect function with an argument, redirect(authorize_url)

Flask URL variable type None?

I'm trying to pass a number through URL and retrieve it on another page. If I try to specify the variable type, i get a malformed URL error and it won't compile. If I don't specify the var type, it will run, but the variable becomes Type None. I can't cast it to an int either. How can I pass it as an Integer...? Thanks in advance.
This gives me a malformed URL error:
#app.route('/iLike/<int: num>', methods=['GET','POST'])
def single2(num):
This runs but gives me a var of type none that I can't work with:
#app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
**num = request.args.get('num')**
You are mixing route parameters and request arguments here.
Parameters you specify in the route are route parameters and are a way to declare variable rules. The values for these parameters are passed as function arguments to the route function. So in your case, for your <num> url part, the value is passed as the function argument num.
Request arguments are independent of routes and are passed to URLs as GET parameters. You can access them through the request object. This is what you are doing with request.args.get().
A full example would look like this:
#app.route('/iLike/<int:num>')
def single2(num):
print(num, request.args.get('num'))
Opening /iLike/123 would now result in 123 None. The request argument is empty because you didn’t specify one. You can do that by opening /iLike/123?num=456, which would result in 123 456.
You recieve None here:
num = request.args.get('num')
because you're not passing num as element of querystring.
When use request.args.get('num')?
If we would have URL like this one:
localhost:8080/iLike?num=2
But it's not your case. You pass num already to a function as an argument. So in your case just use:
#app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
print(num)
In your second example, instead of num = request.args.get('num') try to simply use num. Since you specified it as an input to your route/function, you should be able to access it directly.
Try this:
#app.route('/iLike/<int:num>', methods=['GET','POST'])
def single2(num):
print(num)
Other issues aside, the direct cause of the "malformed URL" error is the space you included in the URL:
'/iLike/<int: num>'
Instead of this:
'/iLike/<int:num>'

Categories