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>'
Related
Lately I have been trying to use the GET request in django-python. However I run into a 404 error when I do so. I want the program to print the parameter given to it.
URL PATTERN :
path('add<int:hello>/',views.add,name = 'Add')
VIEWS.PY:
def add(request,num1):
val1 = request.GET["num1"]
return HttpResponse(request,"Hello")
WHAT I AM SEARCHING ON BROWSER:
http://127.0.0.1:8000/add?1
A couple of things are strange or broken here.
Given path('add<int:hello>/', views.add, ...),
Django expects that function views.add has the following signature:
def add(request, hello):
The pattern 'add<int:hello>/' expects urls with "add" followed by an integer, such as:
http://127.0.0.1:8000/add1
http://127.0.0.1:8000/add2
http://127.0.0.1:8000/add3
...
and so on.
request.GET["num1"] expects urls that have num1=... in their query string, such as:
http://127.0.0.1:8000/add1?num1=...
HttpResponse expects a string type as its first parameter,
not an HttpRequest type as in the posted code.
Fixing the problems
This might be close to what you want, and it will work:
path('add<int:num1>/', views.add, name='Add')
def add(request, num1):
return HttpResponse(f"Hello {num1}")
# visit http://127.0.0.1:8000/add1
Another variation:
path('add', views.add, name='Add')
def add(request):
num1 = request.GET['num1']
return HttpResponse(f"Hello {num1}")
# visit http://127.0.0.1:8000/add?num1=123
http://127.0.0.1:8000/add?hello=1
This should work. you need to add the query param name as well.
To get the value you need to use this code:
request.GET["hello"]
I have html template, and python function(driver_links), my functional work but I have the wrong link
html template (driver_id.html):
{{key[0]}}
function:
#app.route("/report/drivers/<driver_id>")
def driver_links(driver_id):
context = {
"report": sort_asc_desc('data', 'asc'),
"test": driver_id
}
return render_template('driver_id.html', **context)
wrong link I have: http://127.0.0.1:5000/report/drivers/SVF
if I change #app.route in function(driver_links) to:
#app.route("/report/drivers/")
I get a correct link, but function doesn't work
example correct link: http://127.0.0.1:5000/report/drivers/?driver_id=SVF
Choose between variable rules or url parameters.
If you use the former, the required, extracted parameter is passed as a variable to the function.
#app.route("/report/drivers/<driver_id>")
def driver_links(driver_id):
# ...
With the latter, you have to ask for the optional parameter from the dictionary request.args and no arguments are passed to the function.
from flask import request
#app.route("/report/drivers/")
def driver_links():
driver_id = request.args.get('driver_id')
# ...
Note that you can specify a default value and a type conversion here. You can find the documentation for this here.
#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}
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="")
My view function what should receive an argument:
def result(request, exercise_field = {"tro": "lolo"}):
return render(request, "lolapp/result.html", exercise_field)
"Exercise_field" is the variable that takes an argument.
Url for that function:
url(r'^result/', view = views.result, kwargs = {'lolo': 'roflo'}, name = 'result')
As you can see, i tried to pass my argument via "kwargs" keyword. So far - haven't worked out.
Shortcut that calls this View:
return redirect('result', kwargs={'lol': 'rofl'})
And finally the error message:
Reverse for 'result' with arguments '()' and keyword arguments '{'kwargs': {'lol': 'rofl'}}' not found. 1 pattern(s) tried: ['result/']
I need to send one argument to "results" view.
And this is typical "NoReverseMatch" error, but no solutions in internet worked for me.
What do i do wrong?
may be just typo:
kwargs={'lol': 'rofl'}
you should try:
kwargs={'lolo': 'rofl'}
return redirect('result', kwargs={'lol': 'rofl'})
should be for kwargs:
mydict = {'lol': 'rofl'}
return redirect('result',passdict=mydict)
or simply you can do with args:
mydict = {'lol': 'rofl'}
return redirect('result',mydict)
Your URL does not accept any arguments at all: the view kwargs are hard-coded. It is therefore impossible for any request - whether a redirect or just a normal request - to pass any kwargs other than the hard coded ones.
You have various options:
change the URL pattern so it does accept arguments;
add an extra pattern with the other kwargs hard coded;
pass the data in the session rather than the kwargs.
The solution to my problem is simple: i should've to use sessions.
Info about sessions: http://machinesaredigging.com/2013/10/29/how-does-a-web-session-work/
How to use sessions in Django: https://docs.djangoproject.com/en/1.6/topics/http/sessions/
Simply store it within request.session["my_data_key"], and i good to go.
request.session is simple python dictionary.