Google App Engine folder url's in Python - python

In google App Engine, If I already have a page setup so everything gets redirected to main.py as shown below:
www.foobar.appspot.com/
will always go to main.py
the main.py is setup pretty much the same way as the hello world tutorial (except it calls some more functions that I wrote but that is irrelevant).
Now my question is, how can I set up multiple pages in the format of "Folders" or do anything with urls really... (I have not had much luck with reading through the documentation)
www.foobar.appspot.com/admin/
would go to a class or something, that would obviously handle all of the admin features (for now I would love a hello world). I really do not no, what script I would have that url go to, I am pretty clueless on urls with google App engine. I have seen posts where people had multiple classes in the main.py script but I could not figure out how to change the yaml file to accomidate that.

Your main.py will need to look at the URL and route it to whatever handler function you use.
This is a common task and most web frameworks have some way to handle it. For example, if you're using webapp2:
http://webapp-improved.appspot.com/guide/routing.html

URLs are mapped to python scripts in app.yaml; the first regex you have in there that matches /admin will determine what's executed.
In the Python files themselves, you also need to handle the URLs that are dispatched to them (how you do this depends on what framework you're using; consult your documentation for how to do routing.)

Related

Flask webapp as user interface for a python module

I have written a python module for extracting archives and processing some data from the extracted files, then optionally deleting the extracted files. Currently I am using it by writing user-code in a separate python script. e.g:
import my_module
with my_module.archive("data.rar") as a:
a.extract()
a.convert("data.csv", "data.xlxs")
a.delete(keep="data.xlsx")
But for non-programmers to use it, I am trying to create a webapp user-interface for it with flask.
What are the best practices for implementing some communication between the user and the module through a webapp? For example
how could my module to communicate to the webapp-user that the extraction or the data processing has finished?
how should the it display the list of extracted files?
how could the user select a file to be processed or to be deleted?
Basically I need to interleave my library code with some user code and I would like the webapp to generate and execute the user-code and to display the output of the processing module.
(I sense a close flag coming since this is a broad topic and it's been a while since "best practices" topics were allowed on SO. )
Based on my on faults I'd recommend to:
implement the backend first, don't waste time on web design if the backend functionality is not crystal clear yet. Read about flask blueprints and create a blueprint for all public calls like list directory, select file, unzip file, etc... test it out, use requests, post stuff, check responses, iterate.
if you are satisfied with basic functionality, start implementing the frontend. For interactivity you can use the very same api calls via javascript you already tested, use XMLHttpRequest (or use jQuery - I am not a big fan of that) for posting stuff. The catch here is that when you post (from the browser), you can define a callback, so you may use the flask response to update the interface.
add some css, eventlisteners to your templates to make it pretty and comfy.
Get ideas from here and here and here and here (just googled for some random pages, some seemed on topic for you).
You probably want to read this too.

Is it possible to run a Python app on a WordPress site?

I have an idea for a web app and plan to learn Python as I go (right now I know html/css, some javascript, some php and sql). The app would be able to manipulate and analyze audio files, among other things.
Ideally, I'd like to make the app available through my wordpress site so that I can take advantage of WordPress's login management and the plugin s2member's subscription management and content restriction capabilities.
Is that possible? Would it even make sense?
If not, is there a better alternative to automate all of that (the subscription management, logins, payment processing, content restriction, etc) without having to code it myself?
I suggest you develop a REST API in Python and extend your Wordpress site to consume that API.
For the Python side, you could go with Flask and use Flask-RESTful.
For the Wordpress side, have a look at this question.
Sure, if you meet a couple of conditions:
The server your wordpress site is on also has python
And you have the ability run arbitrary python scripts on said server.
Here's a (very contrived) example of how to do it from a plugin:
call-python.php (plugin file):
<php
/*
Plugin name: Call Python
Author:..
....
*/
$pyScript = "/path/to/app.py";
exec("/usr/bin/python $pyScript", $output);
var_dump($output);
And the python script app.py:
print("Hello, World")
And that's it! That will dump Hello, world to the body. Obviously you'll need a bit more for a more complicated python app, but it will work.
Like others are saying, there may be better "more correct" ways of doing it. But if your end goal is to run a python app from WordPress it's possible.

uWSGI - Serving multiple python files with only uWSGI behind nginx

Pardon me, this question is going to be too basic but i have not been able to get the solution anywhere. So, here goes ..
I have set up an instance nginx on Ubuntu 14.04 and an instance of uWSGI on port 9090.
I can direct the traffic from nginx to that one instance of uWSGI, and it works.
But every hello world example i see has something like this
> def application(env, start_response):
> start_response('200 OK', [('Content-Type','text/html')])
> return "Hello World From uWSGI"
and it is just one file... so, if i have multiple python files that needs to be served, distributed through a tree of subdirectories [basically my project]. How can I set that directory structure available for use through HTTP requests?
I would NOT like to use any frame work like Django of flask. But serve simple python file, similar to how a pure html site distributed through subdirectories would serve html.
i might also be missing some concept of how routing can be done. As i feel that has never come up till now.
The directory structure has logic that manipulates a database or interacts with thrid party apis.
Need some guidance to start off.
[Please let me know if there is totally a different way to archive what i am in need of, or if i am on the right track]
Thanks.
The application function is responsible for everything. Of you want to do routing, you do it there, by parsing the request path in env['PATH_INFO'] and then importing and calling the relevant Python functions.
But that would be rather a silly thing to do, seeing is that is exactly what Flask would do for you. You don't need to use anything else from the framework it you really don't want to.

Simple and effective web framework

I'm looking for a suitable cross-platform web framework (if that's the proper term). I need something that doesn't rely on knowing the server's address or the absolute path to the files. Ideally it would come with a (development) server and be widely supported.
I've already tried PHP, Django and web2py. Django had an admin panel, required too much information (like server's address or ip) and felt unpleasant to work with; PHP had chown and chmod conflicts with the server (the code couldn't access uploaded files or vice versa) and couldn't handle urls properly; web2py crashed upon compiling and the manual didn't cover that -- not to mention it required using the admin panel. Python is probably the way to go, but even the amount of different web frameworks and distributions for Python is too much for me to install and test individually.
What I need is a simple and effective cross-platform web development language that works pretty much anywhere. No useless admin panels, no fancy user interfaces, no databases (necessarily), no restrictions like users/access/levels and certainly no "Web 2.0" crap (for I hate that retronym). Just an all-powerful file and request parser.
I'm used to programming in C and other low level languages, so difficulty is not a problem.
This question is based on a complete failure to understand any of the tools you have apparently "investigated", or indeed web serving generally.
Django has an admin panel? Well, don't use it if you don't want to. There's no configuration that needs to be done there, it's for managing your data if you want.
PHP has chown problems? PHP is a language, not a framework. If you try and run something with it, you'll need to set permissions appropriately. This would be the case whatever language you use.
You want something that doesn't need to know its address or where its files are? What does that even mean? If you are setting up a webserver, it needs to know what address to respond to. Then it needs to know what code to run in response to a request. Without configuring somewhere the address and the path to the files, nothing can ever happen.
In web2py you do not need to use the admin interface. It is optional.
Here is how you create a simple app from zero:
wget http://web2py.com/examples/static/web2py_src.zip
unzip web2py_src.zip
cd web2py/applications
mkdir myapp
cp -r ../welcome/* ./
Optional Edit your app
emacs controllers/default.py
emacs models/db.py
emacs views/default/index.html
...
(you can delete everything in there you do not need).
Now run web2py and try it out
cd ../..
python web2py.py -i 127.0.0.1 -p 8000 -a chooseapassword &
wget http://127.0.0.1:8000/myapp/default/index.html
When you edit controller/default.py you have a controller for example
def index():
the_input = request.vars # this is parsed from URL
return dict(a=3,b=5,c="hello")
You can return a dict (will be parsed by the view with same name as action) or a string (the actual page content). For example:
def index():
name = request.vars.name or 'anonymous'
return "hello "+name
and call
wget http://127.0.0.1:8000/myapp/default/index?name=Max
returns
'hello Max'
/myapp/default/index?name=Max calls the function index, of the controller default.py of the application in folder applications/myapp/ and passes name=Max into request.vars.name='Max'.
I think you need to be more specific about what you want to achieve, and what kind of product(s) you want to develop. A "no setup required" product may come with tons of auto-configuration bloat, while a framework requiring a small setup file could be set up in minutes, too, with much more simplicity in the long run. There is also always going to be some security and access rights to be taken into consideration, simply because the web is an open place.
Also, a framework supporting Web 2.0ish things doesn't have to be automatically a bad framework. Don't throw away good options because they also do things you don't like or need, as long as they allow you to work without them.
PHP had chown and chmod conflicts with the server (the code couldn't access uploaded files or vice versa) and couldn't handle urls properly;
PHP is not a framework in itself, it's a programming language. I don't know which PHP-based framework or product you tried but all the problems you describe are solvable, and not unique to PHP. If you like the language, maybe give it another shot. Related SO questions:
What PHP framework would you choose for a new application and why?
What’s your ‘no framework’ PHP framework?
If you need something that runs everywhere (i.e. on as many servers as possible) PHP will naturally have to be your first choice, simply because it beats every other platform in terms of cheap hosting availability.
If I were you, I wouldn't limit my options that much at this point, though. I hear a lot of good things about Django, for example. Also, the Google App engine is an interesting, scalable platform to do web work with, supporting a number of languages.
Werkzeug:
import werkzeug
#werkzeug.Request.application
def app(request):
return werkzeug.Response("Hello, World!")
werkzeug.run_simple("0.0.0.0", 4000, app)
You can optionally use werkzeug URL routing (or your own, or anything from any other framework). You can use any ORM or template engine for Python you want (including those from other Python frameworks) etc.
Basically it's just Request and Response objects built around WSGI plus some utilities. There are more similar libraries available in Python (for example webob or CherryPy).
What I need is a simple and effective cross-platform web development language that works pretty much anywhere.
Have you tried HTML?
But seriously, I think Pekka is right when he says you need to specify and clarify what you want.
Most of the features you don't want are standard modules of a web app (user and role mgmt., data binding, persistence, interfaces).
We use any or a mix of the following depending on customer requirements: perl, PHP, Flash, Moonlight, JSP, JavaScript, Java, (D/X)HTML, zk.
I am python newbie but experienced PHP developer for 12 years but I have to admit that I migrated to python because of the bottle framework. I am African so you don't have to be extra smart to use it... Give it a try, you'll love it. Hey and it also runs on appspot with no config!
Install python
Download bottle.py (single file)
Create
#your file name : index.py
from bottle import route, run
#route('/')
def index():
return 'jambo kenya! hakuna matata na bottle. hehehe'
run()
Sit back, sip cocoa and smile :)
I'd say Ruby on Rails is what you're looking for. Works anywhere, and no configuration needed. You only have it installed, install the gems you need, and off you go.
I also use ColdFusion, which is totally multi-platform, but relies on the Administrator settings for DSN configuration and stuff.
TurboGears: Everything optional.
Give bottle a try. I use it for my simple no-frills webapps. It is very intuitive and easy to work with in my experience.
Here is some sample code, and it requires just bottle.py, no other dependencies.
from bottle import route, run
#route('/')
def index():
return 'Hello World!'
run(host='localhost', port=8080)
Just stumbled upon Quixote recently. Never used it though.
Use plain old ASP. IIS does not care where files are stored. All paths can be set relative from the virtual directory. That means you can include "/myproject/myfile.asp", whereas in PHP it's often done using relative paths. Global.asa then contains global configuration for the application. You hardly ever have to worry about relative paths in the code.
In PHP you'd have include(dirname(FILE) . '/../../myfile.php") which is of course fugly. The only 'solution' I found for this is making HTML files and then using SSI (server side includes).
The only downside to ASP is the availability, since it has to run on Windows. But ASP files just run, and there's not complex Linux configuration to worry about. The language VBScript is extremely simple, but you can also choose to write server side JavaScript, since you're familiar with C.
I think you need to focus on Restful web applications. Zend is a PHP based MVC framework.

Is it possible to write dynamic web pages in Python with the Really Simple HTTP Server?

I know that with the SimpleHTTPServer I can make my directories accessible by web-browsers via Internet. So, I run just one line of the code and, as a result, another person working on another computer can use his/her browser to see content of my directories.
But I wander if I can make more complicated things. For example, somebody uses his/her browser to load my Python program with a set of parameter (example.py?x=2&y=2) and, as a result, he/she sees the HTML page generated by the Python program (not the Python program).
I also wander if I can process html form submitted to the SimpleHTTPServer.
While it is possible, you have to do pretty much everything yourself (parsing request parameters, handle routing, etc).
If you are not looking to get experience in creating web-frameworks, but just want to create a small site you should probably use a minimalistic framework instead.
Try Bottle, a simple single-file web framework: http://bottlepy.org
Maybe the VerseMatch project and related recipes over at ActiveState is something you would be interested in examining? It implements a small application using the standard library for dynamic running.
have you considered using CGIHTTPServer instead of SimpleHTTPServer? Then you can toss your scripts in cgi-bin and they'll execute. You have to include content-type header and whatnot but if you're looking for quick and dirty it's real convenient

Categories

Resources