Python Forum

Full Version: Python wsgi example: problem with javascript
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hello all,
          Please I am having a problem modifying wsgi example. The original example is as follows:

import cgi

form = b'''
<html>
   <head>
       <title>Hello User!</title>
   </head>
   <body>
       <form method="post">
           <label>Hello</label>
           <input type="text" name="name">
           <input type="submit" value="Go">
       </form>
   </body>
</html>
'''

def app(environ, start_response):
   html = form

   if environ['REQUEST_METHOD'] == 'POST':
       post_env = environ.copy()
       post_env['QUERY_STRING'] = ''
       post = cgi.FieldStorage(
           fp=environ['wsgi.input'],
           environ=post_env,
           keep_blank_values=True
       )
       html = b'Hello, ' + post['name'].value + '!'

   start_response('200 OK', [('Content-Type', 'text/html')])
   return [html]

if __name__ == '__main__':
   try:
       from wsgiref.simple_server import make_server
       httpd = make_server('', 8080, app)
       print('Serving on port 8080...')
       httpd.serve_forever()
   except KeyboardInterrupt:
       print('Goodbye.')
I am trying to replace the outputted html with javascript code from a library for rendering open street maps like this:

form = b'''
<html>
<title>OpenLayers Simplest Example</title>
<div id="demoMap" style="height:250px"></div>
<script src="OpenLayers.js"></script>
<script>
   map = new OpenLayers.Map("demoMap");
   map.addLayer(new OpenLayers.Layer.OSM());
   map.zoomToMaxExtent();

markers = new OpenLayers.Layer.Markers( "Markers" );
   markers.id = "Markers";
   map.addLayer(markers);
var coordinates = [];

   map.events.register("click", map, function(e) {
        //var position = this.events.getMousePosition(e);
var toProjection = new OpenLayers.Projection("EPSG:4326");
        var position = map.getLonLatFromPixel(e.xy);
var position_t = map.getLonLatFromPixel(e.xy).transform(map.getProjectionObject(), toProjection);
coordinates.push(position_t);
alert(position_t);
        var size = new OpenLayers.Size(21,25);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var icon = new OpenLayers.Icon('images/mark.png', size, offset);   
        var markerslayer = map.getLayer('Markers');

        markerslayer.addMarker(new OpenLayers.Marker(position,icon));

  });
  $( '#coord_id' ).val( JSON.stringify(coordinates) );
  
</script>
<form method="POST" action="" class="">
   <input type="hidden" name="coord" id="coord_id" value="" />
   <input type="submit" name="commit" value="Go" class="float" />
</form>
</html>
When I run the simple server I get a blank page. On trouble-shooting using the browser's view page source function, I discovered that the javascript file is not being loaded. I don't know what to do to get it to load (and for the other code between the second set of script tags to work) or if it's even possible to run javascript in such a manner.
Any pointers to the resolution of this problem would be greatly appreciated.
(Jun-13-2017, 10:44 AM)imonike Wrote: [ -> ]I don't know what to do to get it to load (and for the other code between the second set of script tags to work) or if it's even possible to run javascript in such a manner.
Any pointers to the resolution of this problem would be greatly appreciated.
Use code tag BBcode help
It's pretty hopeless to use cgi/wsgi to do stuff like this at a low level.
Use Flask it's build on top of WSGI,
and has all tool to deal with modern web development as eg integrate JavaScript.
Thank you Snippsat. I had the suspicion that I would probably need to learn flask. I just wanted to be sure this stuff couldn't be done with raw python.

Cheers!!
Quote:I just wanted to be sure this stuff couldn't be done with raw python.
It can be done it's just a lot harder,
like if doing GUI all use a framework(Tkinter,WxPython,PyQt,Kivy..ect) rather than figure how do this stuff with raw Python.

Armin author of Flask dealt with WSGI for long time trough Werkzeug,
before writing Flask.

Both Flask and Django has build in WSGI web-servers,
so can to all development local.

If happy with some result and wan to deploy(share with world),
then deal with more production ready WSGI web-servers like Gunicorn/Ngnix(i use this combo with Digital Ocean).
Or if don't deal with deploy side all,
just upload code as example to PythonAnywhere/AWS Lambda(lets you run code without provisioning or managing servers).
(Jun-13-2017, 01:16 PM)imonike Wrote: [ -> ]Thank you Snippsat. I had the suspicion that I would probably need to learn flask. I just wanted to be sure this stuff couldn't be done with raw python.

Cheers!!

It absolutely can. However, just as with other languages which don't use cgi anymore (perl, php, ruby, c++), raw cgi is incredibly slow. The reason is because your app gets started for each request. The main way to do things now-a-days is to have a long running process that listens for connections and responds to them. That way the start-up time doesn't matter, as you're already running. wsgi is one of the ways to accomplish that in a way that web servers (like nginx or apache) understand.

So yes, you can do cgi if you want. Just be aware that going that route will almost definitely lead to a slower and less responsive application, regardless of what language you use.
Thank you Snippsat and Nilamo for the clarification. I think I should explain my motivations. I am trying to solve the "Truck Dispatch Problem". I already have a python script that can determine optimal routes for a delivery truck if the coordinates are fed to it via a csv file. I now want to integrate this script with openstreetmaps. I want to be able to pick places on a map and when I press the submit button, have the coordinates of the selected places passed on to my python script and I was trying to do this without having to learn to use a framework (as I am still in the exploratory programming phase). I am not hellbent on cgi/wsgi, it just seemed like the way to go. To render he maps, I was using the javascript frame work OpenLayers.js. I had seen a cgi/wsgi example with a html form that seemed to suit my purposes (the posted code).I tried to replace the form with javascript but the javascript doesn't seem to get executed.
Quick example of running OpenLayers.js with Flask.
open_layer\
|-- app.py
|-- templates\
   |-- index.html    
app.py:
from flask import Flask,render_template,request

app = Flask(__name__)
@app.route('/')
def open_layter():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug=True)
index.html:
<!DOCTYPE html>
<html>
 <head>
   <title>Simple Map</title>
   <link rel="stylesheet" href="https://openlayers.org/en/v4.2.0/css/ol.css" type="text/css">
   <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
   <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
   <script src="https://openlayers.org/en/v4.2.0/build/ol.js"></script>
 </head>
 <body>
   <div id="map" class="map"></div>
   <script>
     var map = new ol.Map({
       layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
       target: 'map',
       view: new ol.View({
         center: [0, 0],
         zoom: 2
       })
     });
   </script>
 </body>
</html>
python app.py in browser http://127.0.0.1:5000/
So all work,then can think of doing other stuff like input from a form.
You see the simplicity of running Flask,
i look at OpenLayers.js tutorial for a couple of minutes before writing this.
Many thanks Snippsat. Extremely kind of you to go through all that trouble. I going to start learning flask and try this immediately. I will let you know how it goes.

Many thanks again.

Cheers!!!

Clap
Hello Snippsat. Please could I have the link to the particular Openlayer tutorial you referenced? I ran your example and it works. I am having issues with mine.

Thanks
This one,just the first example i did find.

Here a tips as OpenLayers do most changes in JavaScript,so you need a way to send data to JavaScript.
Jinja2 is a part of Flask also written bye Armin.
With Jinja you can send data(example a Python dictionary) from server to JavaScript.
Example.
app.py:
from flask import Flask, render_template,jsonify,request

app = Flask(__name__)
@app.route('/')
def hello():
   data = {'map': '50', 'site': 'openlayer'}
   return render_template("index.html", data=data)

if __name__ == '__main__':
   app.run(debug=True)
index.html:
<!doctype html>
<html>
 <head>
   <script>
     var some_javascript_var = '{{ data["map"] }}';
   </script>
   <body>
     <p>Hello World</p>
     <button type="button" onclick="alert('Map: {{ data['site'] }} ' + some_javascript_var)"> Click Me!</button>
   </body>
</html>
Pages: 1 2