Django How to Store HTML files in Amazon S3 - python

I have a question regarding HTML files and Django. Can the django views file serve html files that are not stored locally and stored on amazon s3?
For example instead of:
def index(request):
return render(request, 'index.html')
have something like:
def index(request):
return render(request, 'http://bucket.s3.amazonaws.com/file.html')
Obviously its currently appending the url link to the folder it things html are served from.
Is this sort of thing even possible?
Thanks

I do not believe this is feasible. Web servers exists just for this reason: to serve HTML pages to clients. Amazon S3 exists for file storage, such as images, videos, js files, css files, fonts etc. Not HTML!
On the other hand, suppose this was feasible, your Web server should make a GET request to the HTML stored in S3 (to get the html), then fill it with context variables and then send it to the client (response).
The job of a Django view is to take a Web request and return a Web response. Not making another GET request to get the html which will send as a respose right away (!).
Hope that clarifies your question!

Related

How to retrieve a login form written in simple html file when clicked on the login button using flask?

After running the index.html file when we click on login button, the form needs to be displayed for which I have created a login.html file, now how do I link this file in flask? I have put all the html files in the templates folder. Obviously the info added by the user needs to be entered into the MySQL workbench database.
Correct me if I'm wrong, but it sounds like you'd like to have users directed from the index.html page to the login.html page. If so, you could simply add a link to the login page URL within the index page and have Flask handle the connection via a route.
A simple example would be to insert something like the following into your views.py/routes.py file, or your main app file if you are doing a very simple application (in which case you can leave out the import, obviously):
from app import app
#app.route('/path/to/login')
def login()
return render_template('login.html', title='Login')
where app is your Flask application object and /path/to/login is a relative URL appended to your main domain URI.
To make things a bit more maintainable and reusable, you might reference the link to the login page in index.html by using the Jinja2 template engine to automatically populate your anchor tag's href with the desired URL path:
Login
This should get you from index.html to the login.html page with the form.
For more info, check the docs.

ReactJS server side rendering fo single page application

What I've already done
I have a frontend entirely built with React.JS.
All the business logic is handled by Django and exposed by Django REST Framework via an API.
I'm able to build for different mobile environnements (Android and iOS via Cordova)
The web application is accessible via my Django project (the same that exposes the api), the frontend is sill the same ReactJS code bundled via webpack.
The App has a single entry point, main.js which is a bundled version of my react.js components and dependencies, so my index.html typically looks like this :
<body>
<script type="text/javascript" src="/static/bundles/main-3997ad3476694c3c91cf.js"></script>
</body>
What I want to do
I want to provide a server-side rendering of my web application to let web crawlers correctly index my app on web (I'm not looking for server-side rendering for mobile builds)
How can I handle this considering the fact that my app is a Single Page Application ? I do not want to reinvent the wheel nor to duplicate my code. What kind of node.js server do I have to write in order to achieve this automatic server-side rendering ? Is there any way to provide the server side rendering directly in Django (via some tools reading and interpreting the final results of the page as displayed on the client-side and returning this raw html ?)
You have probably solved your problem by now, but I wanted to share my solution for this.
I have a very similar setup, and have something that seems to work pretty well so far. I basically have a django w/ DRF backend api and isomorphic React/Flux javascript app. I also run a node server next to the python backend server, which acts only as a 'template rendering' service. In essence, replacing the django render function.
So I simply replace the django View with a special IsoView which calls off via http to the node server and returns the rendered html.
from rest_framework.renderers import JSONRenderer
import requests
class IsoView(View):
def user_json(self):
if self.request.user.is_anonymous():
return {'anonymous': True}
else:
return UserSerializer(self.request.user, context={'request': self.request}).data
#classmethod
def render(cls, request, template, data):
req_data = JSONRenderer().render(data)
try:
headers = {'content-type': 'application/json'}
query_params = request.GET
resp = requests.post(_build_url(request.path), params=query_params, data=req_data, headers=headers, timeout=0.1)
reply = resp.json()
if resp.status_code == 302:
return redirect(reply.get('redirect'))
if 'error' in reply:
raise Exception("\n\nRemote traceback: {}".format(reply.get('traceback')))
except requests.exceptions.RequestException as err:
logger.warn('IsoView request exception: {}'.format(err))
reply = {}
return render(request, template, {
'react': reply.get('result'),
'data': data
})
And use it like so:
class HomePage(IsoView):
def get(self, request, *args, **kwargs):
return self.render(request, 'app.html', {
'user': json_data...
})
This also assumes a django template which uses something like this
<html>
<head>
<script>
window.data = {{ data|json }};
</script>
</head>
<body>{{ react|safe }}</body>
</html>
What this does is it renders the html returned from node in the body tag and also dumps the json data required for bootstrapping the app on the client in the window.data object.
This is a really simplified version of the system, but it should work. You should be careful with XSS attacks on the window.data bit, so make sure to escape all your json data but other than that, you should be all good.
Then the node template server looks really similar to any of the tutorials online that you can find for server-side react. Just a simple express app.
Alternatively, you don't need to mess around with django templates at all if you render the full ... in node and return that as a string.
Hope that helps.

Is possible to save render_to_response template from django to server?

I created web application in Python, Django framework. Web application gets data from MongoDB database, it gets about 10000 documents from MongoDB database and works very slow. Now looking for ways to speed up my web app. So, is it possible to store result from method render_to_response as HTML temporarily on server? It looks like this:
I have a HTML form; when the user types data in the form and clicks on submit button, web app executes a view that gets data from the Mongo database, and sends that data via variable mongo_data to home.html:
return render_to_response('home.html', {'mongo_data': mongo_data, 'request': request},
context_instance=RequestContext(request))
home.html show data that are stored in variable mongo_data. In the web application, I have a lot of identical queries, for identical queries I get identical result for home.html. So I want to store home.html to folder for example temp on server, and when user types data in the HTML form and clicks the submit button, first to check is if home.html for his data is in temp folder; if it is, then load that home.html, if not then go to view which will generate new home.html with specific mongo_data.
If this is possible , it will speed up my web app a lot ..
The Django caching framework was made exactly for this purpose; see https://docs.djangoproject.com/en/dev/topics/cache/.
In your case, you either cache the entire view for a period of time:
#cache_page(60 * 15)
def my_mongo_view(request):
return render_to_response('home.html', ...)
(From https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache)
or you use the Low-level Cache API (https://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api):
from django.core.cache import cache
def my_mongo_view(request):
ret = cache.get('home-rendered')
if ret is None:
ret = render_to_response('home.html', ...)
cache.set('home-rendered', ret)
return ret
You'll find more options for caching (e.g. inside your templates) if you just read the doc.
P.S. you can also parametrize your cache by a variable or user ID or something else.

How should an index.html file be served from Python Pyramid for an AngularJS app?

I am getting into single-page apps with AngularJS but rather than using Node or similar, I am most comfortable with Python on the server. So, given I am somewhat familiar with Pyramid, I plan to use the pyramid_rpc module to return JSON objects to the client app. That's all straight forward enough, however, what then is the best way to serve the starting index file which contains the AngularJS initial AngularJS app? Usually, static files are served from a static directory, but is there any problem serving a index.html file from the root? Or should I use a view-callable and '/' route with a renderer to a html template? All that being said, is Pyramid overkill for this kind of application? Any advice would be great.
If you're planning to return some JSON responses then Pyramid is a great option. But I wouldn't recommend using pyramid_rpc. JSON-RPC is a protocol that is intended for RPC communication between servers. Straight json responses fit most clients (like browsers) better such as just a bunch of routes that return JSON responses in response to GET/POST requests. This is also a good place to serve up index.html, probably with a good http_cache parameter to prevent clients from requesting that page too often (of course you can go further with optimizing this route, but you should probably save that for later).
config.add_route('index', '/')
config.add_route('api.users', '/api/users')
config.add_route('api.user_by_id', '/api/users/{userid}')
#view_config(route_name='index', renderer='myapp:templates/index.html', http_cache=3600*24*365)
def index_view(request):
return {}
#view_config(route_name='api.users', request_method='POST', renderer='json')
def create_user_view(request):
# create a user via the request.POST parameters
return {
'userid': user.id,
}
#view_config(route_name='api', request_method='GET', renderer='json')
def user_info_view(request):
userid = request.matchdict['userid']
# lookup user
return {
'name': user.name,
}

How to get information via POST request without reloading entire webpage. (Python/Django)

The situation is simply that we want to send information to Django (our web framework), have it perform functions on the information, and receive information back from Django.
Just now our form to POST to the server looks like this.
<form method="post" onAction="/write" name="form1">
{% csrf_token %}
<button type="submit">Send Info for processing</button>
</form>
And we want this process to send a variable or transmit information.
This successfully reaches our views.py and gets to a function where information can be done.
But currently we don't know how to take information in from the POST nor how to send it back without loading a whole new page.
Since you don't want to refresh the page when you are posting a request, you would want to make a Asynchronous Request to the Server. JQuery, Javascript library has some neat functions which would help you make an asynchronous request. After the server receives the request, it can perform computation can send an HttpResponse with HTML, XML or JSON data as mentioned by Brandon
This is a wiki page for the Tutorial on Ajax with Django
https://code.djangoproject.com/wiki/AJAX
You need to return an HttpResponse. It's up to you whether or not to return XML, JSON, HTML, etc. Your request has to be made via Ajax.
https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpResponse

Categories

Resources