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)...
Related
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"
)
I am trying to export data from python to javascript.
I have a python pandas dataframe df that I export to a file "formatted.json" using the following code
with open('../data/formatted.json', 'w') as outfile:
df.to_json(outfile)
Here's an excerpt of the ../data/formatted.json file:
{"game_id":{"0":"bda33adca828c09dc3cac3a856aef176","1":"03f67404824aee9be3cba7bc3a2a3499","2":"658843f757b400ecbc5587e8ed3e5521","3":"51e4e3d8fe4d2ecf7f926b5049696f0e","4":"d2f82f3973ced311faac8c6bd90b16b9","5":"c1e42fa78b9a527487211c2dfccad8fb","6":"ee25ac1aa64a6b33cfd7d42881e4f7b9"}}
I then try to import this data in javascript to read into my react component using
import oddsdata from '../data/formatted.json'
//returns error
Module not found: Can't resolve '../data/formatted.json'
I think the problem is because i dont have an export in my formatted.json file? How can I configure either the python export or the js import to overcome this issue?
the js file is saved in src/betting/betinterface/betinterface.js and the data is saved in src/data/formatted.json
The link to the data file formatted.json is not correct as per our discussion in the comment.
You should change it to
import oddsdata from '../../data/formatted.json'
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.
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.
I want to build a desktop application using python, html and javascript. So far i have followed the tuts on flask and have a hello world working example. What should i do now to make it working? how do the html files "talk" to the python scripts below them?
here is my code so far :
from flask import Flask, url_for, render_template, redirect
app = Flask(__name__)
#app.route('/hello/')
#app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
#app.route('/')
def index():
return redirect(url_for('init'))
#app.route('/init/')
def init():
css = url_for('static', filename='zaab.css')
return render_template('init.html', csse=css)
if __name__ == '__main__':
app.run()
You can use HTML forms just as you normally would in your Jinja templates - then in your handler you use the following:
from flask import Flask, url_for, render_template, redirect
from flask import request # <-- add this
# ... snip setup code ...
# We need to specify the methods that we accept
#app.route("/test-post", methods=["GET","POST"])
def test_post():
# method tells us if the user submitted the form
if request.method == "POST":
name = request.form.name
email = request.form.email
return render_template("form_page.html", name=name, email=email)
If you wanted to use GET instaed of POST to submit the form you would just check request.args rather than request.form (See flask.Request's documentation for more information). If you are going to be doing much with forms though, I recommend checking out the excellent WTForms project and the Flask-WTForms extension.