Django curl request - django

Im trying to use curl to hit an endpoint in my Django application and havent been successful returning my data.
curl 127.0.0.1:8000/myapp/?email=myname#gmail.com&part=123434
my server shows a 301 when the curl goes through, however; none of the print statements are ran in my view, and i am not able to get the querystring parameters using request.GET.get().
[21/Aug/2018 00:26:59] "GET /myapp/?email=myname#gmail.com HTTP/1.1" 301 0
view.py
def index(request):
if request.method == 'GET':
print('hello world')
email = request.GET.get('email')
part = request.POST.get('part')
print(email)
print(part)
df = generate_dataframe('apps/myapp/data.csv')
df = get_dataframe_by_part(part, df)
bool = check_all(email, df)
response_data = {}
response_data['DoesUserExist'] = bool
return HttpResponse(json.dumps(response_data), content_type="application/json")
urls.py
urlpatterns = patterns('',
url(r'myapp/', include('myapp.urls')),
)
myapp/urls.py
urlpatterns = patterns('',
url(r'^$', 'myapp.views.index', name='index'),
)

The description for 301 error is
The HTTP response status code 301 Moved Permanently is used for
permanent URL redirection, meaning current links or records using the
URL that the response is received for should be updated.
from 301 error
Hence the issue could be different. check first, whether you can able to load from chrome and the urls are correct

Related

Page not found (404), The empty path didn’t match any of these [duplicate]

Very basic question and I was surprised I wasn't able to find an answer. I'm just starting looking at django and did an out-of-box intallation. Created a project and created an app.
The default content of urls.py is very simple:
urlpatterns = [
path('admin/', admin.site.urls),
]
And if I open the django site home page, I get the content with a rocket picture. However, like I said, I have created another app in the project, let's say called 'bboard'. And I have created a simple 'hello world' function in bboard/views.py
def index(request):
return HttpResponse('Hello world')
to enable it for access through browser, I have modified the original urls.py file in the following way:
from bboard.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('bboard/', index),
]
This way I can access localhost:port/admin and localhost:port/bboard URLs, but if I try to open the home page with localhost:port now, I get Page not found error.
Using the URLconf defined in samplesite.urls, Django tried these URL patterns, in this order:
admin/
bboard/
The empty path didn't match any of these.
if I comment out the second item in urlpatterns list, everything works. So why does the additional pattern impact this and what needs to be done to fix it?
You need to add an empty url in root urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('bboard.urls'))
]
Before you add your own routes Django will serve the default home page at the '/' url. After you add your own route config, django no longer serves up its default sample home page.
From the django's django/views/debug.py:
def technical_404_response(request, exception):
"""Create a technical 404 error response. `exception` is the Http404."""
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried or ( # empty URLconf
request.path == '/' and
len(tried) == 1 and # default URLconf
len(tried[0]) == 1 and
getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
)):
return default_urlconf(request)
Note the final else block that returns a default_urlconf if the only url path included is the admin path and the requested url is /. This default_urlconf is the sample Rocket page you mentioned. As soon as you add any of your own routes the if statement in the else block will be false so the default_urlconf is not returned and instead falls through to the normal 404 handler.
Here's the default_urlconf
def default_urlconf(request):
"""Create an empty URLconf 404 error response."""
with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open() as fh:
t = DEBUG_ENGINE.from_string(fh.read())
c = Context({
'version': get_docs_version(),
})
return HttpResponse(t.render(c), content_type='text/html')
The other reason that you might be getting this error is because
You haven't passed an empty URL inside your application URL
Kindly (this is a simple but a very crucial one) check for typos

How can I print 404 requests in Django?

I have a Django app and that work perfect, I want get all request 404 for print in terminal.
like: 127.0.0.1:8000/admin/hello # result is 404 because I haven't this URL I want get /admin/hello because I haven't this URL.
How can I do?
I mean :
User enter 127.0.0.1:8000/admin/hello then terminal set a= /admin/hello and print(a)
You can create a middleware for this. Here is an example based on BrokenLinkEmailMiddleware implementation:
from django.utils.deprecation import MiddlewareMixin
class BrokenLinkMiddleware(MiddlewareMixin):
def process_response(self, request, response):
if response.status_code == 404 and not settings.DEBUG: # for production
domain = request.get_host()
path = request.get_full_path()
referer = request.META.get('HTTP_REFERER', '')
if not self.is_ignorable_request(request, path, domain, referer):
ua = request.META.get('HTTP_USER_AGENT', '<none>')
ip = request.META.get('REMOTE_ADDR', '<none>')
# Store response in Database
YourModel.objects.create(domain=domain, path=path, ua=ua, ip=ip, referer=referer)
return response
And add it your settings:
MIDDLEWARE = [
...
'path.to.BrokenLinkMiddleware',
]
Thanks from #ruddra for answer.
I explain simple:
I add to views.py:
from django.utils.deprecation import MiddlewareMixin
class BrokenLinkMiddleware(MiddlewareMixin):
def process_response(self, request, response):
if response.status_code == 404 : # for production
domain = request.get_host()
path = request.get_full_path()
print('path : ',path)
# print('domain : ',domain)
ua = request.META.get('HTTP_USER_AGENT', '<none>')
ip = request.META.get('REMOTE_ADDR', '<none>')
# Store response in Database
# print('ua:',ua)
# print('ip:',ip)
return response
Then add to settings.py segment MIDDLEWARE :
MIDDLEWARE = [
...
'MynameAPP.views.BrokenLinkMiddleware'
...
]
And finish work. thanks again #ruddra.

I don't understand django's 404 display

I want to move to my 404 page when accessing a URL that is not set.
We are trying to implement it in multiple applications.
I tried a few, but I can't.
Where is the best way to write code?
#setting
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1']
#project url.py
from django.conf import settings
from django.urls import re_path
from django.views.static import serve
# ... the rest of your URLconf goes here ...
if settings.DEBUG:
urlpatterns += [
re_path(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
handler404 = 'person.views.handler404'
handler500 = 'person.views.handler500'
#application view.py
def handler404(request):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
def handler500(request):
response = render_to_response('500.html', {},
context_instance=RequestContext(request))
response.status_code = 500
return response
Don't use render_to_response, it's obsolete. Use render instead.
def handler404(request):
response = render(request, '404.html', status_code=404)
If your tutorial or book is telling you to write this code, then it's out of date, and you should look for a different resource to learn Django.
In your case, the handlers are not doing anything different to the regular handler. Therefore you should unset handler404 and handler500. The default handlers will use your custom 404.html and 500.html templates as long as they are in the templates directory.

Django routing - The empty path didn't match any of these

Very basic question and I was surprised I wasn't able to find an answer. I'm just starting looking at django and did an out-of-box intallation. Created a project and created an app.
The default content of urls.py is very simple:
urlpatterns = [
path('admin/', admin.site.urls),
]
And if I open the django site home page, I get the content with a rocket picture. However, like I said, I have created another app in the project, let's say called 'bboard'. And I have created a simple 'hello world' function in bboard/views.py
def index(request):
return HttpResponse('Hello world')
to enable it for access through browser, I have modified the original urls.py file in the following way:
from bboard.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('bboard/', index),
]
This way I can access localhost:port/admin and localhost:port/bboard URLs, but if I try to open the home page with localhost:port now, I get Page not found error.
Using the URLconf defined in samplesite.urls, Django tried these URL patterns, in this order:
admin/
bboard/
The empty path didn't match any of these.
if I comment out the second item in urlpatterns list, everything works. So why does the additional pattern impact this and what needs to be done to fix it?
You need to add an empty url in root urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('bboard.urls'))
]
Before you add your own routes Django will serve the default home page at the '/' url. After you add your own route config, django no longer serves up its default sample home page.
From the django's django/views/debug.py:
def technical_404_response(request, exception):
"""Create a technical 404 error response. `exception` is the Http404."""
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried or ( # empty URLconf
request.path == '/' and
len(tried) == 1 and # default URLconf
len(tried[0]) == 1 and
getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
)):
return default_urlconf(request)
Note the final else block that returns a default_urlconf if the only url path included is the admin path and the requested url is /. This default_urlconf is the sample Rocket page you mentioned. As soon as you add any of your own routes the if statement in the else block will be false so the default_urlconf is not returned and instead falls through to the normal 404 handler.
Here's the default_urlconf
def default_urlconf(request):
"""Create an empty URLconf 404 error response."""
with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open() as fh:
t = DEBUG_ENGINE.from_string(fh.read())
c = Context({
'version': get_docs_version(),
})
return HttpResponse(t.render(c), content_type='text/html')
The other reason that you might be getting this error is because
You haven't passed an empty URL inside your application URL
Kindly (this is a simple but a very crucial one) check for typos

django - method PUT - Forbidden (CSRF cookie not set.):

My function view for method PUT is:
return JsonResponse ({})
Using HttpRequester (addon for firefox)
I get CSRF verification failed. Request aborted.
print(request) give following result:
Forbidden (CSRF cookie not set.): /test/src/4213
I don't know what I should do. Could you help me please ?
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test/src/(\d+)', MyView.as_view(), name='put_'),
]
class MyView(View):
....
def put(self, request, *args, **kwargs):
print(request)
return JsonResponse({})
I have no form so I can't include {%csrf_token%}. I have no html file. I try to test it with HttpRequester (firefox addon)
Make sure that if you are submitting a form you {%csrf_token%} as a hidden input in your form.
Also, check to make sure that CsrfViewMiddleware is in your MIDDLEWARE_CLASSES in settings.py
If this view is not for a form but to be accessed directly by something you can remove csrf checks with csrf_exempt decorator :
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test/src/(\d+)', csrf_exempt(MyView.as_view()), name='put_'),
]