Get module name as parameter in request - python

What is the best way to get my module name as a function paramteter (entity) in request function?.
I tried the following but is not working at all (Page not found). Something is wrong in the url regex? :
url(r'^<entity>=accounts/(?P<pk>[0-9a-z\-]+)/activate_entity/$', activate_entity)
def activate_entity(request, entity, pk):
entity_model = apps.get_model(app_label='entities', model_name=entity)
entity_object = entity_model.objects.get(pk=pk)

Your regex pattern is wrong. try the following
url(r'^(?P<entity>[a-zA-Z_]+)/(?P<pk>[0-9a-z\-]+)/activate_entity/$', activate_entity)
and the url will be,
/{entity_name}/{pk}/activate_entity/

Related

PAGE NOT FOUND- ERROR(404);GET request; django-python

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"]

looks like a valid python syntax to me but gives me invalid error using in django

Maybe I'm wrong but this looks like a valid python code to me but I get invalid syntax....I'm trying to split url,removing www when domain is displayed. This is my code:
return urlparse(urlsplit(self.url)).netloc if self.url else "be kind to one another"
but this is wrong...
maybe I'm approaching wrong for implementing this function..
any help would be appreciated
Edit 1: Now I get 'SplitResult' object has no attribute 'find'
It looks like you just need to delete urlsplit function from your code and it will work as expected:
from urlparse import urlparse
url = "http://stackoverflow.com/questions/34446468/looks-like-a-valid-python-syntax-to-me-but-gives-me-invalid-error-using-in-djang"
long_url = urlparse(url).netloc if url else "be kind to one another"
long_url.split('.', 1)[1] if long_url.split('.', 1)[0] == 'www' else long_url

i can't take the "?" character in the URL of django url

I try to code to django a redirect fonction. I provide the url, and i want to redirect to the provided URL.
in my urls.py:
urlpatterns = patterns('',
url(r'^redirect/(?P<name>.*)$', redirect),
# ...
)
when i test the function with a standard link (ex: google.com), it works perfectly.
when i test the function with a link that containt a "?" character, only the part before the "?" is taken into account.
Example :
"GET /redirect/http://www.polyvore.com/lords_liverpool_hey_jude_tee/thing?id=53713291 HTTP/1.1" 302 0
name = http://www.polyvore.com/lords_liverpool_hey_jude_tee/thing
the ?id=53713291 is not taken into account....
i though that .* means all kind character, wrong?
Do you know what happens ? and how to take the entiere url what ever the character it contains?
thank you very much for your help.
You seems to don't understand how URL works. Everything after the ? is parsed as arguments for your current view. If you print data in your request.GET dict, you'll find something like:
{'id': 53713291}
The only way to fix that is to urlencode your URL in the argument and decode it before the redirection.
>>> import urllib
>>> urllib.quote_plus("http://www.polyvore.com/lords_liverpool_hey_jude_tee/thig?id=53713291")
'http%3A%2F%2Fwww.polyvore.com%2Flords_liverpool_hey_jude_tee%2Fthing%3Fid%3D5313291'
# You should make your URL with this value, for example:
# /redirect/http%3A%2F%2Fwww.polyvore.com%2Flords_liverpool_hey_jude_tee%2Fthing%3Fid%3D5313291
# And in your view, use unquote_plus before the redirection:
>>> urllib.unquote_plus('http%3A%2F%2Fwww.polyvore.com%2Flords_liverpool_hey_jude_tee%2Fthing%3Fid%3D5313291')
'http://www.polyvore.com/lords_liverpool_hey_jude_tee/thing?id=5313291'
More information about Query String on Wikipedia.
You're passing in a regex, so you need to escape the special characters (ie, \?)
But if you're trying to pass in querystring parameters you'll want to handle that differently: https://stackoverflow.com/a/3711911

Pyramid route matching and query parameters

I have a Pyramid web service, and code samples are as follows:
View declaration:
#view_config(route_name="services/Prices/GetByTicker/")
def GET(request):
ticker = request.GET('ticker')
startDate = request.GET('startDate')
endDate = request.GET('endDate')
period = request.GET('period')
Routing:
config.add_route('services/Prices/GetByTicker/', 'services/Prices/GetByTicker/{ticker}/{startDate}/{endDate}/{period}')
Now I know this is all screwed up but I don't know what the convention is for Pyramid. At the moment this works inasmuch as the request gets routed to the view successfully, but then I get a "Dictionary object not callable" exception.
The URL looks horrible:
#root/services/Prices/GetByTicker/ticker=APPL/startDate=19981212/endDate=20121231/period=d
Ideally I would like to be able to use a URL something like:
#root/services/Prices/GetByTicker/?ticker=APPL&startDate=19981212&endDate=20121231&period=d
Any Pyramid bods out there willing to take five minutes to explain what I'm doing wrong?
from you sample code, i think you use the URL Dispatch
so it should be like this
config.add_route('services/Prices/GetByTicker/', 'services/Prices/GetByTicker/')
then the URL like:
#root/services/Prices/GetByTicker/?ticker=APPL&startDate=19981212&endDate=20121231&period=d
will match it
--edit--
you don't have to use a name like "services/Prices/GetByTicker" for route_name,and you can get the GET params use request.params['key']
View declaration:
#view_config(route_name="services_Prices_GetByTicker")
def services_Prices_GetByTicker(request):
ticker = request.params['ticker']
startDate = request.params['startDate']
endDate = request.params['endDate']
period = request.params['period']
Routing:
config.add_route('services_Prices_GetByTicker', 'services/Prices/GetByTicker/')
The query string is turned into the request.GET dictionary. You are using parenthesis to call the dictionary instead of accessing items via the brackets. For a url such as
#root/services/Prices/GetByTicker/?ticker=APPL&startDate=19981212&endDate=20121231&period=d
request.GET['ticker'] # -> 'APPL' or an exception if not available
request.GET.get('ticker') # -> 'APPL' or None if not available
request.GET.get('ticker', 'foo') # -> 'APPL' or 'foo' if not available
request.GET.getall('ticker') # -> ['APPL'] or [] if not available
The last option is useful if you expect ticker to be supplied multiple times.
request.params is a combination of request.GET and request.POST where the latter is a dictionary representing the request's body in a form upload.
Anyway, the answer is that request.GET('ticker') syntactically is not one of the options I mentioned, stop doing it. :-)

Unable to view item in browser based on its key in Python GAE

I'm using python GAE with webapp.
I have a form for a user to create a object in the database, something like:
class SpamRecord(db.Model):
author = db.ReferenceProperty(Author, required=True)
text = db.StringProperty()
After it's created, the user is redirected to a page whose URL contains that object's key... using code such as:
spam = SpamRecord(author=author, text=text)
spam.put()
new_spam_key = spam.key()
self.redirect("/view_spam/%s" % new_spam_key)
And this mostly works, with me being able to view items at:
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQYy8oJDA
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY_boJDA
However, there's an occasional key that won't work. Here are 2 recent examples of pages that won't load and return HTTP 404 not found errors:
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-5MJDA
sitename.com/view_spam/ag1waWNreXByZXNlbnRzchQLEgxBbm5vdW5jZW1lbnQY-boJDA
My html-mappings.py contains the following mapping:
(r"/view_spam/(\w+)", ViewSpamPage)
And the ViewSpamPage looks something like:
class ViewSpamPage(webapp.RequestHandler):
def get(self, spam_id):
self.response.out.write("Got here")
Can anyone offer any insight as to why this is occurring and how it may be prevented?
Thanks very much!
In regular expressions, \w doesn't match hyphens. (It will match underscores.) For that second pair of keys, this'll result in only passing part of the key to your handler.
In your URL pattern, try r"/view_spam/(.*)" instead.

Categories