I need to generate css based on client queries. I use the #import url() directive inside some style tags to call a method to produce a text string response of css. I can see the css is generated correctly in firebug, but it doesn't take effect.
If I serve the exact same css from my site media directory use the #import directive everything works fine.
my html header code:
<style type="text/css">
#import url("{{ css_url }}")
/*#import url("/site_media/css/style.css")*/
</style>
my django python code:
string = u'#exampleTextInput{ background-color:#ff0000;}\n'
return HttpResponse(string)
You probably need to set a Content-Type response header; that'd be my first guess:
string = u'#exampleTextInput{ background-color:#ff0000;}\n'
return HttpResponse(string, content_type='text/css')
Related
I want to send a verification email. The email consists of HTML. I saved the HTML into a file named email_templates/verify.html (path). The problem is, that there are some constants in the HTML file are unknown until runtime. For instance, in the email, I refer to the username to which I send my email, but since each email is referring to someone else, I can't include the name in the template. One solution that comes to mind is to use some formatting technique in the lines of
<div>
hello {usrname}!
<div>
and then in the python code do something like:
lines = open('email_templates/verify.html', 'r').read()
lines.format('joe')
But this code, although is, in fact, can work, has some issues:
every {} in the HTML file can be a mistake to be formatted
the code in the current form is not very readable
code is not elegant
for an HTML reader that don't know python the formatting placeholders will be confusing
Is there is any better way to approach this?
This can and should be done through templating.
As you mentioned that maybe python placeholders will be confusing but I tell you they are not confusing, templating engines make sure HTML looks like HTML and these template tags look like template tags. Templating engines lay down the rules which placeholders you can and can't use. Also they are way fast than the file opening method you suggested; because they are optimized to do so.
Let's understand by example:
There are several templating engines out there. Jinja2 is one of the best ones.
First, install Jinja2.
pip install jinja2
Second, create a python file(name it anything you want) and a folder named 'templates'. Under 'templates' folder create your verify.html
Your folder structure should look like this:
folder1
|
|--> pythonfile.py
|--> templates
|
|--> verify.html
Third, put some sample code in the HTML file. I have this example put in my verify.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index</title>
</head>
<body>
<h1>Dear {{ user }}!</h1>
<h4>
Hope you are fine.
</h4>
<p>
Thank you for signing up. Here is your {{ coupon_code }}
</p>
</body>
</html>
Now in this html file you see I have normal html tags. But there are two sets of curly braces occurring twice. The word written inside the curly braces will be considered a variable by jinja. The value of this variable will be supplied by our python file to this html file.
Also, to be consistent, jinja doesn't allow you to just use any braces. I mean if I had put "<>" instead of "{{ }}" it would not have worked. So there are some rules to be followed.
Read more here: Jinja allowed tags and filters
Fourth, copy this code into the python file we created.
#Imports
from jinja2 import Environment, FileSystemLoader, Template
#name of the folder where index file is located.
file_loader = FileSystemLoader('templates')
#This object is needed to create a template object.
env = Environment(loader=file_loader)
#path of the HTML file reletive to the folder.
template = env.get_template('./index.html')
#Data dictionary to be supplied to our HTML file.
input_dict = {
'user': 'Harry',
'coupon_code': '12313ASDSA4'}
#This function renders the data substituted HTML form.
output = template.render(input_dict)
print(output)
Now run this python file.
Currently I have some Python files which connect to an SQLite database for user inputs and then perform some calculations which set the output of the program. I'm new to Python web programming and I want to know: What is the best method to use Python on the web?
Example: I want to run my Python files when the user clicks a button on the web page. Is it possible?
I started with Django. But it needs some time for the learning. And I also saw something called CGI scripts. Which option should I use?
You are able to run a Python file using HTML using PHP.
Add a PHP file as index.php:
<html>
<head>
<title>Run my Python files</title>
<?PHP
echo shell_exec("python test.py 'parameter1'");
?>
</head>
Passing the parameter to Python
Create a Python file as test.py:
import sys
input=sys.argv[1]
print(input)
Print the parameter passed by PHP.
It probably would depend on what you want to do. I personally use CGI and it might be simpler if your inputs from the web page are simple, and it takes less time to learn. Here are some resources for it:
cgi — Common Gateway Interface support
Python - CGI Programming
However, you may still have to do some configuring to allow it to run the program instead of displaying it.
Here's a tutorial on that: Apache Tutorial: Dynamic Content with CGI
If your web server is Apache you can use the
mod_python module in order to run your Python CGI scripts.
For nginx, you can use mod_wsgi.
Thanks to WebAssembly and the Pyodide project, it is now possible to run Python in the browser. Check out my tutorial on it.
const output = document.getElementById("output")
const code = document.getElementById("code")
function addToOutput(s) {
output.value += `>>>${code.value}\n${s}\n`
output.scrollTop = output.scrollHeight
code.value = ''
}
output.value = 'Initializing...\n'
// Init pyodide
languagePluginLoader.then(() => { output.value += 'Ready!\n' })
function evaluatePython() {
pyodide.runPythonAsync(code.value)
.then(output => addToOutput(output))
.catch((err) => { addToOutput(err) })
}
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Default Pyodide files URL ('packages.json', 'pyodide.asm.data', etc.)
window.languagePluginUrl = 'https://pyodide-cdn2.iodide.io/v0.15.0/full/';
</script>
<script src="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script>
</head>
<body>
Output:
</div>
<textarea id='output' style='width: 100%;' rows='10' disabled></textarea>
<textarea id='code' rows='3'>
import numpy as np
np.ones((10,))
</textarea>
<button id='run' onclick='evaluatePython()'>Run</button>
<p>You can execute any Python code. Just enter something
in the box above and click the button.
<strong>It can take some time</strong>.</p>
</body>
</html>
There's a new tool, PyScript, which might be helpful for that.
Official website
GitHub repository
You can't run Python code directly
You may use Python Inside HTML.
Or for inside PHP this:
http://www.skulpt.org/
You should try the Flask or Django frameworks. They are used to integrate Python and HTML.
There is a way to do it with Flask!
Installation
First you have to type pip install flask.
Setup
You said when a user clicks on a link you want it to execute a Python script
from flask import *
# Importing all the methods, classes, functions from Flask
app = Flask(__name__)
# This is the first page that comes when you
# type localhost:5000... it will have a tag
# that redirects to a page
#app.route("/")
def HomePage():
return "<a href='/runscript'>EXECUTE SCRIPT </a>"
# Once it redirects here (to localhost:5000/runscript),
# it will run the code before the return statement
#app.route("/runscript")
def ScriptPage():
# Type what you want to do when the user clicks on the link.
#
# Once it is done with doing that code... it will
# redirect back to the homepage
return redirect(url_for("HomePage"))
# Running it only if we are running it directly
# from the file... not by importing
if __name__ == "__main__":
app.run(debug=True)
You should use Py Code because it could run Any python script In html Like this:
<py-script>print("Python in Html!")<py-script>
Im not sure if it could run modules like Ursina engine ect But what i know is
That It allows you to type Python in Html. You can check out its offical Site for more info.
We can use Python code in HTML files. We have to use Python’s libraries within our browsers.
As we use Pyscript, we don’t need to worry about deployments. Everything happens in a web browser. We can share our HTML files with anyone containing fancy dashboards or any chars data. They can directly run it in a web browser without any complex setup.
Pyscript allows us to write python code with the help of 3 main components:
Py-env: It defines the python packages list which needs to run your
code.
Py-script: In this tag, the user will write their python code.
Py-repl: It will Create a REPL component. The REPL component
executes the code user enters and displays the result of the code in
the browser.
Let's start:
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
Our Hello world program will look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>Python HTML app Hello World</title>
</head>
<body>
<py-script>
print("Hello World!")
</py-script>
</body>
</html>
This project is still in the alpha stage, so maybe we can see many more new things in the upcoming days. Let know more about how to use python in HTML file.
I've installed the markdown preview plugin for gedit running on Lubuntu 13.04. It works as expected.
However, for ease of viewing, I altered the appearance of the resulting html panel (left panel) by including a link to a local stylesheet at the top of each markdown file. But this approach obviously means that I have to alter all my existing markdown files.
To avoid that, I looked at ~/.local/share/gedit/plugins/markdown-preview/__init__.py which has the code for the plugin, and I see lines #39 and #40 (reproduced below):
# Can be used to add default HTML code (e.g. default header section with CSS).
htmlTemplate = "%s"
That gives me the impression that I can somehow tell the plugin to look at a stylesheet and style the html accordingly. But I don't know what to do (if indeed htmlTemplate = "%s" has to be changed).
Set htmlTemplate to something like the following
# Can be used to add default HTML code (e.g. default header section with CSS).
htmlTemplate = """
<html>
<head>
<link rel="stylesheet" type="text/css" charset="utf-8" media="screen" href="http://paste.ubuntu.com/static/pastebin.css">
</head>
<body>
%s
</body>
</html>
"""
I'm currently working on my website hosted on GAE.
It has not been update since a while, so now, I'm trying to made a refresh of it :D
To do the trick, I try to use the MVC model using Python and WSGI, WebAPP2 and Render.Template.
Everything goes right, except for the CSS part.
Indeed, I can't render some part of my CSS using the GAE (django) method.
My Python controller is calling the HTML file and replace the variables by the dict() values correctly.
But now, and to be able to only have restricted amount of CSS file, I'm trying to do the same thing.
Unfortunatly I don't know how I'm suppose to call the CSS File.
I'm currently calling my CSS on my HTML as usual:
<link rel="stylesheet" media="screen" type="text/css" href="/assets/css/struct/index.css">
And trying to dynamically render this part of the file:
header#navigation{
height:auto;
min-height:480px;
width:100%;
min-width:100%;
background-image:url('/assets/img/content/{{content_cat_name}}/cat_img.jpg');
background-repeat:no-repeat;
background-position: left top;
background-size:contain;
background-color:#efefef;
}
and everything is then call by my python code like this:
class URIHandler(webapp2.RequestHandler):
def get(self, subdomain, page):
name = subdomain
pattern = os.path.join(os.path.dirname(__file__), '../views' ,'index.html')
template_values = {
'content_cat_name':name,
'cat_menu_title':name,
'cat_menu_text':name,
}
self.response.out.write(template.render(pattern, template_values))
So, if someone could help me to correctly call my CSS and replace the variables using my python script, I'll be really happy :D
Thanks in advance.
template.render can only replace tokens in the file that you specify in the path parameter (the first parameter). You're serving the .css file out of a static directory, so no token replacement happens, because that file's not getting passed through that code.
You could inline the parts of your CSS that contain tokens in your index.html file.
I was having what I think is the same problem. I found this GAE documentation very helpful. In short you need to go into your app.yaml file create a new handler:
url: /foldername
static_dir: foldername
And then in your link tag:
href="foldername/index.css"
I'm trying to export data to an XML file in the Google appengine, I'm using Python/Django. The file is expected to contain upto 100K records converted to XML. Is there an equivalent in App Engine of:
f = file('blah', 'w+')
f.write('whatever')
f.close()
?
Thanks
Edit
What I'm trying to achieve is exporting some information to an XML document so it can be exported to google places (don't know exactly how this will work, but I've been told that google will fecth this xml file from time to time).
You could also generate XML with Django templates. There's no special reason that a template has to contain HMTL. I use this approach for generating the Atom feed for my blog. The template looks like this. I pass it the collection of posts that go into the feed, and each Post entity has a to_atom method that generate its Atom representation.
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xml:lang="en"
xml:base="http://www.example.org">
<id>urn:uuid:4FC292A4-C69C-4126-A9E5-4C65B6566E05</id>
<title>Adam Crossland's Blog</title>
<subtitle>opinions and rants on software and...things</subtitle>
<updated>{{ updated }}</updated>
<author>
<name>Adam Crossland</name>
<email>adam#adamcrossland.net</email>
</author>
<link href="http://blog.adamcrossland.net/" />
<link rel="self" href="http://blog.adamcrossland.net/home/feed" />
{% for each_post in posts %}{{ each_post.to_atom|safe }}
{% endfor %}
</feed>
Every datastore model class has an instance method to_xml() that will generate an XML representation of that datastore type.
Run your query to get the records you want
Set the content type of the response as appropriate - if you want to prompt the user to save the file locally, add a content-disposition header as well
generate whatever XML preamble you need to come before your record data
iterate through the query results, calling to_xml() on each and adding that output to your reponse
do whatever closing of the XML preamble you need to do.
What the author is talking about is probably Sitemaps.
Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.
And about what I think you need is to write the XML to request object like so:
doc.writexml(self.response.out)
In my case I do this based on mime types sent from the client:
_MIME_TYPES = {
# xml mime type needs lower priority, that's needed for WebKit based browsers,
# which add application/xml equally to text/html in accept header
'xml': ('application/xml;q=0.9', 'text/xml;q=0.9', 'application/x-xml;q=0.9',),
'html': ('text/html',),
'json': ('application/json',),
}
mime = self.request.accept.best_match(reduce(lambda x, y: x + y, _MIME_TYPES.values()))
if mime:
for shortmime, mimes in _MIME_TYPES.items():
if mime in mimes:
renderer = shortmime
break
# call specific render function
renderer = 'render' + renderer
logging.info('Using %s for serving response' % renderer)
try:
getattr(self.__class__, renderer)(self)
except AttributeError, e:
logging.error("Missing renderer %s" % renderer)