I am just starting Python and I was wondering how I would go about programming web applications without the need of a framework. I am an experienced PHP developer but I have an urge to try out Python and I usually like to write from scratch without the restriction of a framework like flask or django to name a few.
WSGI is the Python standard for web server interfaces. If you want to create your own framework or operate without a framework, you should look into that. Specifically I have found Ian Bicking's DIY Framework article helpful.
As an aside, I tend to think frameworks are useful and personally use Django, like the way Pylons works, and have used Bottle in the past for prototyping—you may want to look at Bottle if you want a stay-out-of-your-way microframework.
One of the lightest-weight frameworks is mod_wsgi. Anything less is going to be a huge amount of work parsing HTTP requests to find headers and URI's and methods and parsing the GET or POST query/data association, handling file uploads, cookies, etc.
As it is, mod_wsgi will only handle the basics of request parsing and framing up results.
Sessions, cookies, using a template generator for your response pages will be a surprising amount of work.
Once you've started down that road, you may find that a little framework support goes a long way.
You will have to look into something like CGI or FastCGI, which provides an API to communicate to the webserver.
Google App Engine enables you to write simple apps, and even provides a local webserver where you can try things out.
People here love frameworks. One shortcoming I have noted is that Python lacks a handy-dandy module for Sessions as a library built-in, despite it being available in PHP and as CGI::Session in Perl.
You will end up doing:
import cgi # if you want to work with forms and such
import cgitb; cgitb.enable() # to barf up errors to the web
print 'Content-type: text/html\n\n' # to start off any HTML.
You will have to write session stuff on your own.
For a PHP programmer, I think mod_python is a good way to get started without any framework. It can be used directly as Apache 2 module. You can have code tags (like <? ?> in PHP) and even conditional HTML output (HTML inside if statement):
<%
if x == y:
# begin
%>
... some html ...
<%
# end
%>
(simplified example taken from onlamp.com's Python Server Pages tutorial)
You should try web.py, it provides a bare minimum of features that does not get in your way.
http://webpy.org/
You can just make the entire thing yourself as a CGI script written in python. On an Apache server you go into the httpd.conf file and add these two lines at the bottom.
AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict
Then the standard output is redirected to the client, i.e. the print(...) method sends text to the client. Then you just read the .html, .css, and .js files stored on the server and print() each line. Connect to your database on the backend. Set up your security/authorization protocols... Basically you will need to make the entire framework yourself, only it will be customized to fit your needs perfectly.
Probably a good idea to come up with some special character to parse for when reading the files on the server and before printing to insert any dynamic content, such as:
HTML
<div>
<p> <<& pythonData $>> </p>
</div>
Python
htmlFile = open("something.html", "r")
for line in htmlFile:
if "<<&" in line:
# figure out what characters that special symbol is in the line
# replace them with dictionary value or variable or something
print(line)
else:
print(line)
Here is the documentation for the official library to work with Common Gateway Interface (CGI) in python: https://docs.python.org/3/library/cgi.html It includes an example that shows reading form data sent to the server into a python script.
Don't forget to tell your scripts where the python interpreter is on the Apache server (should be in /bin somewhere), in other words point at python with the sh-bang:
#!/bin/python3.10
Or wherever your server's python interpreter is located at.
Related
I have written an application in python to collect data from a javascript form and returned the processed text. It is based entirely off of the code here (but a lot more complex, so I have to use python for this).
https://kooneiform.wordpress.com/2010/02/28/python-and-ajax-for-beginners-with-webpy-and-jquery/
(note to people who like to edit...please leave this link in place since it shows all the relevant code sections in python and javascript).
I need to use this in wordpress (since that's what runs my site) and I honestly have no idea how to pull this off. Webpy can run with Apache CGI, but the documentation (http://webpy.org/cookbook/cgi-apache) is only clear if one wants to navigate directly to the python app as its own page.
I'm hoping someone here has expertise in how to embed this all within a Wordpress page/post?
Thanks!!
As far as I know, there is no native way to run Python code inside a WordPress site just like php. In fact, if you are not doing anything unique to Python, I would suggest you to use php, which supports regular expression and can be used in WordPress by installing the plugin "Insert PHP".
If you really want to use Python, then you need an API endpoint where you connect the function to your website. You would have to look into Azure Function App/AWS lambda on which you write a function app to work as a backend. Then whenever someone request your website, your website would do an HTTP request to that API.
Can you explain what exactly you want to do on your website?
I have 10 line python code and a third party python library that I want to use in a html website. I do not want to use a full fledged framework like django to complete the task. I want to use the following library https://github.com/nficano/pytube in my project. Thank You looking forward for some assistance.
The most simple thing come to my mind is following.
1) You'll need to use some sort of WSGI (https://uwsgi-docs.readthedocs.io/en/latest/, for example), to serve your script as a web service.
2) You'll also need a little bit of JavaScript code to make AJAX (for example) requests to that script.
So I recently discovered mod_python, which is great because its not hard to rewrite the PHP code I had and execute through Apache. However, I just found out that my hosting service, (HostGator), does not support this module because they have a single apache user instance per physical shared server.
This begs the question:
Without the use of something like Django, Pylons, etc, is there a way to invoke python routines server side from HTML code and have it return web content?
Example:
Simple form
<form name="message" action="directory/pythonscript.py/function" method="POST">
where, upon submission, the form parses the content in the form, and then the python routine returns a string of the newly assembled HTML file based on the input of the form, and the browser presumably re-renders it.
def function(args):
#parse inputs
#assemble html string
return htmlString
Additional question:
With mod_python, you must pass at least the "req" arg, which points to the apache request structure. Is this functionality still present without mod_python? Would I be able to somehow physically map to that without mod_python?
I'm presuming that all of this is possible because HostGator does support python and a lot of the modules, smtpd for example, have functionality to send emails, communicate over the web, etc, so presumably there is some way to access this API independent of Apache???
99% of searches for this return info about Django, Pylons, etc. If that is indeed the best way to do it, I will explore that option, but all I want to do for now is create some dynamic HTML content with a back end python handler without having to install any other APIs.
Thanks.
EDIT
I should clarify that I am not attached to mod_python at all, it is just something I found. My question is geared towards avoiding non-standard, (standard = shipped with Python 2.7.x, useable through apache or otherwise), APIs if possible.
After some digging, it seems that the quickest way to do this is through php, but not as per the previous answer.
In my HTML I should have:
<html> <form name="form" method="$POST" action="formAction.php" </html>
in formAction.php:
<?
system( 'python ~/scripts/pythonscript.py/function', $return)
echo $return
?>
where $return is the dynamically generated HTML page string. Within the python script, I'll have to parse the posted values from the HTML session somehow. I think that answers my question but I'll wait and see if someone else posts something more interesting.
EDIT: Figured out how to parse the POSTed values:
<?php
$VAR1 = $_GET["var1"];
$VAR2 = $_GET["var2"];
system("python <script>.py -args=[".$VAR1.",".$VAR2"."]", $return)
echo $return
?>
for example.
You could do a php.execute('pythonScript.py') on submit, right?
I would like to change the logo of a website based on which menu is currently activated/seen by the user browsing the website.
For instance I have www.urltowebsite.com/menu1 = Header Logo 1
And then I have www.urltowebsite.com/menu2 = Header Logo 2
And on top of this I want to add an else statement stating that: If any other menu is selected, use header logo 3.
How can I make this possible with Python? I cant seem to wrap my head around what to define where and how to call up the different functions on the HTML website.
Oh and I insist doing this with Python. And preferably without any framework such as Django. But if needs be I can install web.py
EDIT:
Am I forced to go with php then? I would like to once and for all start utilizing Python on my web projects.
The website is made in simple HTML as I said first. The Javascript functions are only used to serve the HTML menu's through AJAX. Again this does not matter much for what I am trying to do, as menu's have classes and I can define those in php and thus change my logo/header.
What I want to do is to use Python in this instance. Here is a code snippet from the site:
<div id="header">
<span class="title"><img src="http://www.url.com/subfolder/images/logo.png"/>
</span>
</div>
And some more relevant to this:
<div id="menu">
<ul>
<li>001</li>
<li>002</li>
<li>003</li>
<li>004</li>
<li>005</li>
<li>006</li>
<li>007</li>
<li>008</li>
</ul>
</div>
So can I use python here?
You're asking to do the wrong thing the wrong way.
In order to change the logo based on the URL in Python , you need Python to generate the page and know what that url is.
There are two ways to do that in Python:
Use an existing Web Framework
Write your own Web Framework
"Python" doesn't know or care what your URL is - the frameworks and support libraries ( Django, Pyramid, Bottle, Flash, Tornado, Twisted, etc) figure out what the URL is by an integration with an underlying web server ( though some have their own webserver coupled in ). Similarly, PHP doesn't really know or care what the URL is - that information comes from an integration with Apache or FCGI/Nginx/etc. PHP tends to ship with most/all of that integration done. It's also worth noting that PHP is not just a language, but a web framework. Python is just a language.
Most Python frameworks will be written to the WSGI spec and have a "request" object that has all the data you want ( and many use the WebOb librbary for that ).
If you plan on doing everything with static HTML files, then you have a few options:
have a single static directory. use javascript to figure out the addressbar location, and render the corresponding logo / write the headers & footers.
have a "template" directory of all your HTML. use a Python script build a static version of each website with the custom headers/footers and configure your webserver to serve a different one for each domain.
No, Python cannot run inside the HTML web page. If you're really serving plain HTML pages then you must use javascript to execute code in the browser once the page is loaded. However, since you mention using AJAX, it sounds like it's not really true that you're serving plain HTML but rather have some server side code. If so, that server side code is the place to put your HTML-construction logic. To know the best way to do that, you would have to describe what's happening on the server.
Although I haven't used it, I have heard that the pyhp project more or less provides php-like embedded functionality for python.
I want to create a special wiki page on my local Redmine server. It should contain an inventory of some executables from my server. My goal is a script which scans certain folders on my server for these files and put them (with some additional information) in a nice Redmine wiki page.
My first thought was to traverse my server's file system with a simple batch file and to create a SQL expression for putting the results directly into the underlying mySQL database (which contains Redmine's wiki pages). But I consider this too risky and too error-prone.
Then I had the idea to use a script language like python (which I always wanted to learn) to retrieve the information and send it back to the Redmine server, like a web browser would do. This should be a much safer way. But this doesn't seems to be an easy beginner's task when just starting with python - I fail to authenticate myself on the Redmine server.
My last idea was to create a HTML page with python, which could be displayed within a Redmine wiki page with the plugin 'Redmine Wiki Extensions'. But I consider this only as a solution light, because it's not very elegant.
So what I seek is either a new idea to solve this problem or some clues on how to do a proper authentification with python on my Redmine server - maybe I could use a cookie for easier authentification...
I'm not familiar with redmine, but if you are looking for something like having a script that performs some actions the same way you would do in a browser, then mechanize is a library that might be helpful for you unless there's some javascript involved. In that case, then I'd look into something like windmill or selenium to let you drive the web browser.
However, please note using web scraping is also error-prone since any change in the design of the web pages involved might break your scripts.
Regarding the option of using an API as pointed out by the comment from AdamKG, that would be a good option, since there's a REST API that you can use from python if you like. Unfortunately, I don't see anything to let you do what you're looking for and it seems it hasn't yet reached the stable status yet. Anyway, as I said, it's still a good option to consider in the future.