I have a Django API to export file which needs format as input,
Request URL: http://192.168.5.51:1212/rest/tasks/export_file/CIAYEK5W5JS4MdmCF2t8eB?format=xyz
this request returns a error response
detail (with status 404)
but when I use get request without query params,
Request URL: http://192.168.5.51:1212/rest/tasks/export_file/CIAYEK5W5JS4MdmCF2t8eB
The API is triggered and the file is returned(with default format). As far as i know we don't need to change anything in urlpatterns to support query params. I have also put the specified url in first line to eliminate the chance for any other regex catching the request
urlpatterns = [
url(r'^/export_file/(?P<pk>.+)$',views.TaskFileTranscript.as_view()),
How to support query params in django requests. Thank you in advance.
P.S : Im pretty sure the control is not reaching into the get function, Im using DRF.
Thanks Everyone, it is fixed now. got to know its really a bad idea to use 'format' as query param key.
you have to customize it yourself for example in a class-based view get method:
class Test(APIView):
def get(self, request):
formatQuery = request.GET.get('format', None)
# use this format to customize your result
return Response(result)
and also add / to end of your URL:
http://192.168.5.51:1212/rest/tasks/export_file/CIAYEK5W5JS4MdmCF2t8eB/?format=xyz
Related
I have a working python code on my desktop that prints and makes PDFs perfectly. All I want to do is use that code and use Django to allow users to enter a value.
My code uses docusign API to call data. I use postman which needs a key and other parameters to use the API. The value entered by my user will determine what data they get.
What I think I have to do is rewrite my code, put it somewhere, then turn it into a view. The view will be sent to template.
Edit -
My code:
# Get Envelope Data- use account ID from above
# Get Todays Date, Daily Setting
day = datetime.datetime.today().strftime('%Y-%m-%d')
url = "https://demo.docusign.net/restapi/v2/accounts/" + accountId + "/envelopes"
# if Envelope is completed
querystring = {"from_date": Date, "status": "completed"}
headers = {
'X-DocuSign-Authentication': "{\"Username\":\""+ email +"\",\"Password\":\""+Password+"\",\"IntegratorKey\": \""+IntegratorKey+"\"}",
'Content-Type': "application/json",
'Cache-Control': "no-cache",
'Postman-Token': "e53ceaba-512d-467b-9f95-1b89f6f65211"
}
response = requests.request("GET", url, headers=headers, params=querystring)
envelopes = response.text
Sorry, let me try again. I currently have a python3 program on my desktop. I run it with idle and everything is how I want it.
What I want to do with Django is use this code to print its outputs on a webpage and have the user download it’s additional csv file output. I have managed to make a Django localhost and I am stuck at that point. I do not know how to use my python3 code to run to webpage.
The code is made up of API calls, I use postman to help me with sending the right parameters. I will add a picture of code. All I want is for user to enter value such as accountID so that the API can complete the request and give them data for their own request.
I'll try to give you a overview of how this could work with Django.
You could have a form to obtain the users account_id.
class AccountForm(forms.Form):
account_id = forms.IntegerField()
You could display this form through a generic FormView (see also this):
class AccountView(views.FormView):
form_class = AccountForm
template_name = 'account.html'
def form_valid(self, form):
# here you make your request to the external API
account_id = form.cleaned_data['account_id']
url = "https://demo.docusign.net/restapi/v2/accounts/" + account_id + "/envelopes"
headers = ...
querystring = ...
resp = requests.request("GET", url, headers=headers, params=querystring)
ctx = {
'result': resp.text,
}
return render(self.request, 'result.html', ctx)
I don't show the template account.html here. You will have to figure that one out yourself; the links I provided should point you in the right direction.
Now, what remains to be determined is what exactly the method form_valid should return. The code I showed renders a template with the API call response in the context, so in your template result.html you could display the result data any way you like.
You mentioned downloading a CSV file as well. That could be a different view, probably triggered by a link or button in result.html.
I'd like to add a 'Last seen' url list to a project, so that last 5 articles requested by users can be displayed in the list to all users.
I've read the middleware docs but could not figure out how to use it in my case.
What I need is a simple working example of a middleware that captures the requests so that they can be saved and reused.
Hmm, don't know if I would do it with middleware, or right a decorator. But as your question is about Middleware, here my example:
class ViewLoggerMiddleware(object):
def process_response(self, request, response):
# We only want to save successful responses
if response.status_code not in [200, 302]:
return response
ViewLogger.objects.create(user_id=request.user.id,
view_url=request.get_full_path(), timestamp=timezone.now())
Showing Top 5 would be something like;
ViewLogger.objects.filter(user_id=request.user.id).order_by("-timestamp")[:5]
Note: Code is not tested, I'm not sure if status_code is a real attribute of response. Also, you could change your list of valid status codes.
I am using django with rest framework and I try to test POST on existing object but I keep getting 405. my ViewSet looks like this:
class Agents(viewsets.ModelViewSet):
serializer_class = serializer.AgentSerializer
model = serializer_class.Meta.model
....
and in the urls:
router = routers.SimpleRouter()
router.register(r'rest/agents', api_views.Agents, "Agent")
...
urlpatterns += router.urls
I call the post request from within APITestCase class (rest testing), my post request looks like this:
response = self.client.post(url, {'available': True, 'online':True}, format='json')
and printing url shows "/chat/rest/agents/1910_1567/", while 1910_1567 is the valid id of an existing agent (I create the agent during the setup and use its id).
I've seen other questions about rest post getting 405, but all the solutions there were url-related and in my case the url is correct. I even ran the setup outside the test and accessed the url via browser to get the object and the object indeed exist. but when I try to post to it - 405.
any ideas?
thanks!
Most probably your url is somehow matching with some different url's regex, and the request is being dispatched to some other view which disallows post request. Could you mention others urls in your urls.py? Infact you can verify this by adding pdb(debugger) in dispatch method of your view. If you made it to the pdb, then you can assume I was wrong.
If that is not the case, then you can evaluate the issue from dispatch method with debugger. Just in case you have any doubt about how to do that -
class Agents(viewsets.ModelViewSet):
serializer_class = serializer.AgentSerializer
model = serializer_class.Meta.model
def dispatch(self, *args, **kwargs):
import ipdb; ipdb.set_trace()
return super(Agents, self).dispatch(*args, **kwargs)
Solution Found:-
You are passing id in url, so this request would be routed to detail view and detail view only allow GET, PUT, DELETE operations on resource since resource already exists. So to create resource, don't provide the id. Otherwise use PUT request and provide support for creation in PUT.
POST are supposed to be for creation purpose. If you want to update with a ViewSet you'll need to PUT or PATCH (partial update) instead.
Edit:
For more about this, here's some explanation on the HTTP methods used for REST API:
http://restful-api-design.readthedocs.org/en/latest/methods.html
This is also described in the DRF documentation at:
http://www.django-rest-framework.org/api-guide/routers/#simplerouter
I'm using the SimpleRouter tuorial within the docs.
Just to test I've created a temporary Authentication class:
class BackboneBasicAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
user = User.objects.filter(username="james")
return (user, None)
settings look like this
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'core.rest_authentication.BackboneBasicAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
}
Submitting a PUT request returns a 405 METHOD NOT ALLOWED
{"detail": "Method 'PUT' not allowed."}
I've tried with X-HTTP-Method-Override as well. No go.
Any ideas what I'm doing wrong?
I've spent a whole day trying to figure this out, hopefully someone can help! :)
The simple router adds the put attribute to the view for a url matching the pattern you supply with the pk added as an additional pattern element.
For example if you used:
simple_router.register('widgets/', WidgetViewSet)
The framework will create two url patterns:
'^widgets/$'
'^widgets/<?P<pk>[^/]+/$'
I am guessing that you are only trying urls that satisfy the first match for which the viewset instance will only have 'get' ('list') and 'post' ('create') support added by the framework so it will cause the error you are seeing if you try to put/patch or delete. For those methods to work you need to supply the pk so that the framework knows which widget you are modifying or deleting and so that your url matches the view that supports those methods.
This is confusing and you may choose not to use the simple_router at all if you find it too confusing. Then you can specify your own method mapping so that the rest_framework will dispatch to your put methods e.g.
url('^widgets/<?P<pk>[^/]+/$', WidgetViewSet.as_view({'put': 'update',
'get': 'retrieve',
'patch': 'partial_update',
'delete': 'destroy'}...)
To me that seems to be caused by the routed viewset not implementing or not allowing PUT requests. If it was an authentication issue, you would get a 401 UNAUTHORIZED status code.
the url is starts with? /socket.io/1/websocket/327459101594
Just by searching through the document, seems there's no way to let Django ignore sending email error report based on request URL.
Does any one have any clue?
You can write your own logging handler.
To check the url you could sublcass djangos AdminEmailHandler and extend the emit method to check the url first.
class MyAdminEmailHandler(AdminEmailHandler):
def emit(self, record):
record.request
# request information is available as request property
super(MyAdminEmailHandler, self).emit(record)