0

I am new to using django and am unfamiliar as to how my question should be worded.

I have been working on a new web app but noticed that the initial loading of the website is slow. My current view code is here.

from jinja2 import Environment, FileSystemLoader
from django.http import HttpResponse
from tools import fetcher
import requests
import json

def index(request):
    env = Environment(loader=FileSystemLoader('templates'))
    template = env.get_template('index.html')
    template_values = {'popular_stocks': []}
    popular = fetcher.get_tops()

    for instrument in popular:
        r = requests.get('https://api.iextrading.com/1.0/stock/%s/quote' % (instrument['symbol']))
        quote = json.loads(r.content.decode('utf-8'))
        template_values['popular_stocks'].append(quote)

    return HttpResponse(template.render(template_values))

Is there anyway to speed up the loading of my site by loading the initial index.html first WITHOUT any popularstocks and then submitting the fetcher.get_tops() to the template values?

I know of AJAX but I am unsure how to implement it or if that is even what I need.

Any step towards the right direction would be appreciated.

APorter1031
  • 2,107
  • 6
  • 17
  • 38
  • The above ajax question works with different URL's but I don't want to change URL's. I want my current URL to be loaded in chunks – APorter1031 May 22 '18 at 01:00
  • No other URLs need to be exposed to the end user (though, of course, their browser will see them). As far as your users is concerned they're loading one page. – ChrisGPT was on strike May 22 '18 at 01:01
  • (Opinion: Overloading a single URL to do multiple things is a Very Bad Idea™. It is confusing and will become a maintenance nightmare. If it feels like you're fighting against Python, Django, and HTTP itself that's probably a good sign that you're doing something wrong.) – ChrisGPT was on strike May 22 '18 at 01:03
  • I think I may need to re design my web app to better handle all the request data I am processing but your comment DID solve my problem. – APorter1031 May 22 '18 at 01:07

1 Answers1

-1

Yes, I'd definitely go with AJAX in this case.

Other strategy might be caching the stock prices somewhere (MEMCACHE, Redis?), thus just updating according to a cache expiration policy and not on every page load.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292