How to simulate a HTTP Post request from a django view without a template - django

I am writing views, not so keen to write templates right away.
But I need to test my program by submitting post requests.
How do i simulate HTTP Post from within a django view
I am aware that urllib2 and httplib modules of python allow a lot of options, but I am looking for something that elegantly integrates into the django views.
Would U create a method that performs post, where would you call it from?
Update: Some of the answers deal with testing by sending a POST to my application. What if I want to POST to an external service and deal with POST response. How can I do it without writing templates.

Django has a built in mock Client utility that can mimic requests as if they are coming from a browser. If you don't need to fully mimic a browser and just want to invoke your views directly from your tests, consider using a RequestFactory instead.

For such cases I think RequestFactory is ideally suited.
It works just like django's test client with the difference that it let's you create a request object that you can use anywhere. So you could just create your own request object and pass it to your view or form for testing.
I like this method of testing more then using the test client, since it comes closer to pure unit testing. That is, testing a single piece of code. If you're using the test client, there are more layers added before the actual code you're testing is reached.

To avoid the pain of creating the request object yourself you can use this tip on Django snippets

It sounds like you are looking for either a unit test or an acceptance test. Take a look at unittest which is part of the standard library.
For quick ad hoc tests while developing web apps, I like to use curl. It's a simple command line tool that easily generates all sorts of HTTP requests. You can POST with a command like:
curl -i -d field=value http://localhost:8080/sample/something
Curl is available on a lot of platforms. Check it out at http://curl.haxx.se/

If you are looking at this from the context of writing unittests, you could consider creating the Request object yourself and just calling the view function directly. You could even mock it, and any other parameters the view might take.

Related

Do we need to render templates when using ReactJS as a front-end?

So I just created a website's front-end using ReactJS. Now all I need is a backend database that I will fetch data from using requests.
The question is whether I need to render templates using my backend or just use my server to make requests (eg get, post etc)
PS. I will be using Django as my backend.
Thank you everyone who will help me out.
Doing both is recommended. Based on the requirements and use cases we must use both ways to render.
For example, Some products use initial html as a Server side rendered page with all essential data required inserted as scripts and so on. This helps in loading primary content faster. If we are not following this in applications that require data initially. Then it might take more time to fetch React chunks, scripting and after seeing an API makes request, and then getting data and then displaying the primary content. So when a page needs more data (like More API calls) then server side rendering might be a good way.
For other scenarios like getting user details, All these can be done using React.
No, because you will use DRF (Django Rest Framework) to communicate between frontend and backend. Basically you will write your own APIs in the views.py that will respond with JSON data, at least in major of cases this will be enough. So, you don't need templates, since template are really Djangos' frontend, that you will not be using at all.
But, this heavily depends on what you are doing and what is your setup.

How to run Django views from a script?

I am writing a Django management command that visits a few pages, logged in as a superuser, and saves the results to a set of .html files.
Right now I'm just using the requests library and running the command with the development server running. Is there an easy way to generate the HTML from a view response so I do without actual HTTP requests?
I could create a request object from scratch but that seems like more overhead than the current solution. I was hoping for something simple.
Django has a RequestFactory which seems to suit your needs.
While it's not exactly meant for this purpose, an option would be to use the testing framework's Client to fake a request to the url - be sure to use client.login() before making your requests, to ensure you have superuser capabilities.

Recommended way of talking to a Django application URL, from within a view of the same application?

I have a Django application, and need to deal with the following:
One of my views, needs to make a POST request to another URL endpoint of the same application.
In order to do so, I use the requests module. I assemble the URL of the endpoint I need to call, dump the POST parameters, and perform the call.
This works fine for the most part, however fails miserably when testing, since the view that corresponds to the URL that I talk to, knows nothing about the state of the testing environment.
The code is similar to this:
from django.conf import settings
import json
def view1(request, *args, **kwargs):
url = 'http://api.%s/view2/' % settings.DOMAIN
r = requests.post(
url,
data=json.dumps({'key': 'value'}),
)
// Notice that the ``url`` is a url of the actual deployed application,
// and therefore knows nothing about testing and its state. That's where
// it goes wrong.
The question is, is there a way that this can behave correctly in testing? I use the django.test.client.Client class for creating my test requests. As far as I know, instances of this class talk directly to the URL mapper. Therefore the url that I construct in the view is simply an external http request to the deployed application, instead of the tested application.
Thanks.
One way to solve this is to mock the response from the URL for the purposes of the tests. I'd suggest using a lightweight mocking library, such as this:
http://blog.moertel.com/posts/2011-11-07-a-flyweight-mocking-helper-for-python.html
See the example code. It's very similar to your situation. I've used both of these in combination with requests and flask, but not django.

How to POST data to remote server and display result

I would like to submit some post request from my django app to payment service.
Is there a simple way to do so from within a view and then display the
remote service instead of my own view (something like being redirected to remote
page with post data)
Currently I am messing with some weird approach of displaying a hidden form and
ovveridng it's javascript submit call to implement some of my own stuff, but I think
it is overcomplicated.
I need something like this:
def view(request, **kwargs):
do_my_own_business()
post_data = create_post_dada(**kwargs)
return post_remote_page("https://example.com", post_data)
You can use python's urllib2 to to make a request to a 3rd party website. This is essentially emunlating how you or I would visit the website via code - here's a good tutorial.
If you want to make life easier, there are some libraries build upon urllib2 which make doing these external request easier - namely requests and mechanize. If you are from a PHP background you can also use pyCurl (Not based on urllib2)
Be sure that the payment service you are using doesn't have it's own API or library that you could use instead, as this would be much easier and safer then the above approach which is essentially screen scraping.
Furthermore, be aware that for every request your user makes to your server, your server needs to make to an other external server which means you could potentially time out etc. introducing another level of complexity in managing the connections.

Restful routes and Django

I'm in a process of migrating Rails project into Django. Rails project was built using restful routes and it never touches the database. Instead, it simply redirects to different methods which all call an external service with the specified action method. Now, I have found a number of frameworks for django that provide restful capability plus a bunch of bells and whistles, but it's an overkill for my current case.
As an alternative, I can ignore action method in urls.py by simply providing a regex to validate urls and then parse the request method in views.py, redirecting to the appropriate method. Is this a way to go or are there any other approaches that I can look at?
Class based views look like the idiomatic way to organize restful view functions by request method.
Django snippets has several simple example implementations.