how to reload page in django using js2py? - javascript

i run script every 15 mins to update data on my website but i want to reload ppage in browser after update automatically
i tried to put window.location.reload(true) using js2py and script looks like this:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
import django
django.setup()
from django.core.management import call_command
import time
import js2py
js = """
window.location.reload(true);
"""
def reload():
context = js2py.EvalJs()
context.execute(js)
while True:
call_command("feed_update")
reload()
time.sleep(900)
and i get error:
raise MakeError('TypeError',
js2py.internals.simplex.JsException: TypeError:
Undefined and null dont have properties (tried getting property 'reload')

You don't need this library
def reload():
return HttpResponse("<script>window.location.reload(true);</script>")
or
def reload():
return HttpResponse(
"window.location.reload(true);",
content_type="application/x-javascript"
)

Related

This code keeps popping up whenever I'm trying to run a file where I want to translate JavaScript into Python. What do I do?

I'm trying to translate a JavaScript file into Python so that I can complete my project, but every time I try to do so, this mountain of code keeps appearing and replacing the code I typed in. As a beginner who only started coding in Python 2 months ago, I don't understand whatever's there and I also don't know what to do if this keeps coming up.
I tried these two codes from the Internet for testing and was expecting that they would run properly...
import js2py
from app import *
js2py.translate_file("jsbro.js", "app.py")
app.wish("GeeksforGeeks")
import js2py
js2py.translate_file('jsbro.js', 'app.py')
from jsbro import *
jsbro.wish('LOLZ')
my JS code:
function wish(name) {
console.log("Hello, "+name+"!")
}
but instead, I always got this replacing the code I typed in:
__all__ = ['app']
# Don't look below, you will not understand this Python code :) I don't.
from js2py.pyjs import *
# setting scope
var = Scope( JS_BUILTINS )
set_global_object(var)
# Code follows:
var.registers(['wish'])
#Js
def PyJsHoisted_wish_(name, this, arguments, var=var):
var = Scope({'name':name, 'this':this, 'arguments':arguments}, var)
var.registers(['name'])
var.get('console').callprop('log', ((Js('Hello, ')+var.get('name'))+Js('!')))
PyJsHoisted_wish_.func_name = 'wish'
var.put('wish', PyJsHoisted_wish_)
pass
pass
# Add lib to the module scope
app = var.to_python()
To add, these errors got triggered when I used the two codes mentioned earlier.
from js2py.pyjs import *
NameError: name 'app' is not defined
from js2py.pyjs import *
ModuleNotFoundError: No module named 'jsbro'
Please help.

Django: javascript needs to call a python script, what location do I put it in?

I get really confused about django and file locations a lot, and I'm on django 1.10. But in my static/(django-proj-name)/js/ folder (just showing the way I have my main.js file and I need to call a python script, in conjunction with the jquery tokeninput plugin. Lets call the script keywords.py
This script is going to need to call all instances of a model, Keyword, so I need to be able to import from my models file.
Im' a bit inexperienced with django, but from reviewing some of the projects I've seen over the summer I was startinng to believe that including the line, from (django-proj-name).models import * was the main way to import from models. This at least works for all of the files that I have in my /management/commands/ folder.
But i tried putting keywords.py in my static folder just because I know at the very least I can use the {% static %} template tag to find the file in html. I ran the file without manage.
Traceback (most recent call last):
File "../../management/commands/import_statements.py", line 5, in <module>
from gtr_site.models import *
ImportError: No module named gtr_site.models
Though I have the same importation line, again, in /management/commands/. And that doesn't cause any problems.
So I didn't put the file in the "correct" file location... I didn't put keywords.py in a place where
I know how to import from my models.py file from the keywords.py script's location
My javascript file can find it and run it without crashing. This script needs to be able to successfully import from models.
so where am I supposed to put this script, or how can I specify a location for it?
Let's say you have a js library that expects data in the following format:
{"results": [
{"name": "Foo", "number": 1},
...,
{"name": "Bar", "number": 999}
]}
You started an application called myapi:
$ django manage.py startapp myapi
And suppose you have a Model like this at myapi/models.py:
from django.db import models
class Foo(models.Model):
name = models.CharField(max_lenght=100),
number = models.IntegerField()
In myapp/views.py define the following view:
from django.http import JsonResponse
from django.views import View
from .models import Foo
class FooList(View):
def get(self, request, *args, **kwargs):
qs = list(Foo.objects.values('name', 'number').all())
data = {"results": qs}
return JsonResponse(data)
Then map this view to some url. For the sake of simplicity let's just add this to your main urls.py file:
url('api/v1/foo/$', FooList.as_view(), name='foo-list'),
Now you should be able to reach it from the browser. The example below uses jQuery:
$.getJSON('http://yourdomain.com/api/v1/foo/',
function(data, textStatus, jqXHR) {
console.log(data);
}
)
That is it. I did this from memory so you probably will find a few errors or missing imports - but this should put you on the right track.

Scraping javascript page with PyQt5 and QWebEngineView

I'm trying to render a javascripted webpage into populated HTML for scraping. Researching different solutions (selenium, reverse-engineering the page etc.) led me to this technique but I can't get it working. BTW I am new to python, basically at the cut/paste/experiment stage. Got past installation and indentation issues but I'm stuck now.
In the test code below, print(sample_html) works and returns the original html of the target page but print(render(sample_html)) always returns the word 'None'.
Interestingly, if you run this on amazon.com they detect it is not a real browser and return html with a warning about automated access. However the other test pages provide true html that should render, except it doesn't.
How do I troubleshoot the result always returning "None'?
def render(source_html):
"""Fully render HTML, JavaScript and all."""
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
class Render(QWebEngineView):
def __init__(self, html):
self.html = None
self.app = QApplication(sys.argv)
QWebEngineView.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.setHtml(html)
self.app.exec_()
def _loadFinished(self, result):
# This is an async call, you need to wait for this
# to be called before closing the app
self.page().toHtml(self.callable)
def callable(self, data):
self.html = data
# Data has been stored, it's safe to quit the app
self.app.quit()
return Render(source_html).html
import requests
#url = 'http://webscraping.com'
#url='http://www.amazon.com'
url='https://www.ncbi.nlm.nih.gov/nuccore/CP002059.1'
sample_html = requests.get(url).text
print(sample_html)
print(render(sample_html))
EDIT: Thanks for the responses which were incorporated into the code. But now it returns an error and the script hangs until I kill the python launcher which then causes a segfault:
This is the revised code:
def render(source_url):
"""Fully render HTML, JavaScript and all."""
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
class Render(QWebEngineView):
def __init__(self, url):
self.html = None
self.app = QApplication(sys.argv)
QWebEngineView.__init__(self)
self.loadFinished.connect(self._loadFinished)
# self.setHtml(html)
self.load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
# This is an async call, you need to wait for this
# to be called before closing the app
self.page().toHtml(self._callable)
def _callable(self, data):
self.html = data
# Data has been stored, it's safe to quit the app
self.app.quit()
return Render(source_url).html
# url = 'http://webscraping.com'
# url='http://www.amazon.com'
url = "https://www.ncbi.nlm.nih.gov/nuccore/CP002059.1"
print(render(url))
Which throws these errors:
$ python3 -tt fees-pkg-v2.py
Traceback (most recent call last):
File "fees-pkg-v2.py", line 30, in _callable
self.html = data
AttributeError: 'method' object has no attribute 'html'
None (hangs here until force-quit python launcher)
Segmentation fault: 11
$
I already started reading up on python classes to fully understand what I'm doing (always a good thing). I'm thinking something in my environment could be the problems (OSX Yosemite, Python 3.4.3, Qt5.4.1, sip-4.16.6). Any other suggestions?
The problem was the environment. I had manually installed Python 3.4.3, Qt5.4.1, and sip-4.16.6 and must have mucked something up. After installing Anaconda, the script started working. Thanks again.

Django Ajax - Dajaxice.myapp is not defined

I'm trying to implement Ajax functionality into my website. This seems to be a moderately common problem, but all solutions to it I've found online have been simple, like forgetting something in the tutorial. The error message appears in the JavaScript console.
I'm trying to follow this tutorial: http://django-dajaxice.readthedocs.org/en/latest/installation.html
My actions:
I used pip install django_dajaxice for install
I copy-pasted the settings.py and urls.py code in the tutorial into my own:
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
# AJAX
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
)
urlpatterns += staticfiles_urlpatterns()
and
STATICFILES_FINDERS = ( ... ) # Exact copy paste from tutorial
TEMPLATE_LOADERS = ( ... ) # Exact copy paste from tutorial
TEMPLATE_CONTEXT_PROCESSORS = ( ... ) # Exact copy paste from tutorial
I included the template tags in my base.html, the actual html file inherits from that
Then Quickstart: http://django-dajaxice.readthedocs.org/en/latest/quickstart.html
I created content/ajax.py (content is my app). Code inside is simple:
from dajax.core import Dajax
from content import models
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def fav(request):
dajax = Dajax()
return dajax.json()
Finally, the JS and HTML code which instantiates the AJAX:
<script type="text/javascript" src="{{ STATIC_URL }}dajaxice/dajaxice.core.js"></script>
function js_callback(data) {
Dajax.process(data);
alert(data.message);
}
<a onClick="Dajaxice.content.fav(js_callback);">Favorite</a>
You need to run collectstatic again to regenerate dajaxice.core.js.
And maybe you should remove the static files has been collected before.

Send data from javascript to python in google app engine

i want to create an application in google app engine using python. I have to send a list of json string to python script.I have done the following code but ain't worked.
$.post("/javascriptdata",{v:s},function(data,status) {});
In python script i have a class named javascriptdata to where data has to be send to
import wsgiref.handlers
import json
import sys
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp import Request
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
class mainh(webapp.RequestHandler):
def get(self):
self.response.out.write(template.render("paint.html",{}))
class javascriptdata(webapp.RequestHandler):
def post(self):
self.response.headers['content-Type'] = 'html'
data1=self.request.get('v')
self.response.out.write("""<html><body>""")
self.response.out.write(data1)
self.response.out.write("""</body></html>""")
def main():
app = webapp.WSGIApplication([
('/',mainh),("/save",javascriptdata)], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == "__main__":
main()
The javascriptdata is associated with the url "/save". I have created a submit button named "save" that would redirect to /save but iam not getting any output. I know it may be a silly mistake but Iam struggling to sort it out. Please suggest me how to post and read the data for this code.
This seems suspicious:
$.post("/javascriptdata",{v:s},function(data,status) {});
since you don't have a /javascriptdata URL mapped in the python code. Perhaps you meant
$.post('/save', ...?
Alternatively, you could change the WSGIApplication init to be:
...("/javascriptdata",javascriptdata)...

Categories