[Solved] Python CGI - how to "include" like in PHP

Hi.
When I code PHP I like to use this template system. A short instance would consist of 2 files: "index.php" and "template.php".
template.php:
<?php
echo "<h1>$header</h1>";
echo "<p>$text</p>";
?>
index.php:
<?php
$header = "this is a header";
$text = "this is a text";
include "template.php";
?>
So I can use one template for lots of pages - same layout but different vars.
I cannot find how to do this in Python CGI.
page.cgi:
#!/usr/bin/python
import os, cgi
x = "This is the page text."
eval(open('template.cgi').read())
template.cgi
print("Content-type: text/html\n")
print(x)
This gives me error 500. I am not surprised, this mail.python.org page says:
> I can't figure out how one would approach this in Python (i'm using
> mod_python). There's no equivalent to the "include" function from
> PHP.
Correct, the concept doesn't exist because you are working
with vanilla CGI rather than server scripting.
But maybe there is a way to make something similar?
Last edited by Mr. Alex (2012-06-05 17:52:42)

Template (index.html.tpl)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Main Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
h1 {{
margin: auto;
</style>
</head>
<body>
<h1>Admin</h1>
<ul>
<li><a href="{}">Monthly Report</a></li>
<li><a href="{}">Inventory Zip Files</a></li>
<li><a href="{}">Order Reports</a> -- Last 7 days</li>
<li><a href="{}">Notes/TODO/Information</a></li>
<li><a href="{}">EDI Orders</a></li>
</ul>
</body>
</html>
index.py :
#!/usr/bin/env python2
def main():
template = "index.html.tpl"
pages = ("monthly", "zips", "reports", "vimwiki", "edi.py")
sitename = "/"
pages = ["{}{}".format(sitename, pages) for i in pages]
tpl = "".join(open(template,'r').readlines())
print 'Content-type: text/html\n\n' + tpl.format(*pages)
if __name__ == '__main__':
main()
Maybe not the best way...but it works for me Notice the double {{ }} in the template where you want literal brackets, not placeholders.
Scott

Similar Messages

  • [Solved][Python 3] How to center tkinter window?

    Hi.
    I need to center window on the screen. The window that already has some contents like labels and buttons. Found this code snippet on Stack Overflow:
    w = root.winfo_screenwidth()
    h = root.winfo_screenheight()
    rootsize = tuple(int(_) for _ in root.geometry().split('+')[0].split('x'))
    x = w/2 - rootsize[0]/2
    y = h/2 - rootsize[1]/2
    root.geometry("%dx%d+%d+%d" % (rootsize + (x, y)))
    but it doesn't work. It gives me centered window with no width or height when it has some size if I don't use this snippet. What is wrong in this code?
    Last edited by Mr. Alex (2012-09-27 08:38:18)

    I think the main thing wrong with your code is you were asking for the window size before TK had decided what it should be. Your code works in the interactive interpreter if you run it line by line, but not if you run it all at once.
    I adapted some code of my own for you:
    from tkinter import Tk
    from tkinter.ttk import Label
    root = Tk()
    Label(root, text="Hello world").pack()
    # Apparently a common hack to get the window size. Temporarily hide the
    # window to avoid update_idletasks() drawing the window in the wrong
    # position.
    root.withdraw()
    root.update_idletasks() # Update "requested size" from geometry manager
    x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
    y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
    root.geometry("+%d+%d" % (x, y))
    # This seems to draw the window frame immediately, so only call deiconify()
    # after setting correct window position
    root.deiconify()
    I think it does what you want, although I have two screens side by side so the window is actually split between the two.

  • I would like to know how to include entries in my TOC that refer to paragraph styles that a before the TOC.

    I would like to know how to include entries in my TOC that refer to paragraph styles listed before the TOC.
    Example:
    page i. Title Page
    page ii. Abstract
    page iii. Table of Contents
    I want the TOC on page iii to include the entries "title page" and "abstract". Is this possible?
    Thank you-

    Thesis formatting rules.
    Can you answer another question?
    How do I change the text for a TOC entry? For example,
    I have selected the title on my first page, for example "Summer Report" and selected a paragraph style for it, and added it in the TOC. Now the TOC will have this entry for "Summer Report" and the associated page. But I want it to say "Title Page" instead. Can I edit this text? In order words, have the TOC point to something with whatever name I want to give it, even though it is not the actual name of the section?

  • [Solved] How to include examples for an AUR package

    Hi,
    I read the wiki pages how to create packages for the AUR,
    but I am not sure how to include examples which should be placed
    in /usr/share/doc/<package>/examples/ after the package was installed.
    Should all files be mentioned in the "sources" variable of the PKGBUILD
    or is it better to copy them via the .install file?
    Last edited by fana (2012-01-22 17:38:41)

    fana wrote:Ah, I see. So a good way would be just providing a tarball with all the examples and add that tarball to the source array
    Yup, I don't see how are these are examples different [1] from the other files.
    [1] Well, apart from stuff like https://bugs.archlinux.org/task/25998 ;P

  • [SOLVED]How to include a .Changelog file in a package?

    I want to include a .Changelog file in a package I'm building. But in the wiki, it only mentions that it could exist, and not how to include it.
    Someone knows how to do it?
    Last edited by mcsilva (2010-02-21 14:39:05)

    just put a file named `ChangeLog` in the same directory as PKGBUILD and makepkg
    Edit: wonder It did take me a minute to validate my assumption.
    Last edited by lolilolicon (2010-02-21 12:46:24)

  • How to include something in servlet

    if i have a header file for open html and i have a footer file for close html
    how i can i use it in a servlet just like in php require("header.php");

    By using RequestDispatcher Object u can deo it,d code shown below will help to solve ur problem
    RequestDispatcher rd=getServletContext.getRequestDispatcher("/urlOf theHtmlFile");
    rd.include(HttpServletRequest req,HttpServletResponse resp)

  • Cx_oracle objects in python cgi session

    Hi,
    I am trying some web pages using python cgi and using cx_oracle for data retrieval.
    The page fetches many records and I wanted to display 10 records only at once.
    So I tried to save the cx_oracle connection obj and cursor object in session variable. but session variable is not supporting to save those variables. :(
    How do you guys do this? I dont want to connect and disconnect database every time. any method of doing this?
    I am new to web programming, but good in pl/sql.
    thanks
    ~Gouri

    This isn't possible with a stateless web model in your scenario. Even with a web-savvy language like PHP which allows "persistent connections" you have to re-execute the query each time you "page". This will see any new data other users have inserted.
    You'll need to rethink how the application will be used to see if the paging model will be OK.
    Also make sure the infrastructure can cope with frequent connections. (PHP with Oracle 11g connection pooling is a good alternative)

  • How to include SCOM R2 agent in server image (or vmware template)

    Can anybody tell me how to include the SCOM R2 agent in our Windows images/templates?   For the SCCM client, it is as simple as stopping the service on the reference machine, deleting the cert, and capturing.   I can find no good answer on the Internets on whether the SCOM agent has some sort of unique ID that doesn't like being "duplicated".
    Any help would be appreciated.  (I'd rather NOT include scripted tasks or steps that install the agent AFTER an image is deployed).  
    My RMS is configured to auto-accept agent registrations.

    Hi, I'm looking to do the same.  I created a template with the agent installed; however, I still left the server (W2012 R2) in 'workgroup'.  When loading and configuring the agent, I didn't get any error message since the raw server can communicate
    with the management server nor have I received a 'pending approval' on the mgmt server.
    I like the idea of having this pre-configured and ensuring SCOM properly detects and monitors new server additions since checklists are not followed. 
    Thanks.
    Stanley E. Noel Jr

  • How to include variable in the text column in report painter?

    Dear Expert,
    Would like to seek for your help to include How to include variable in the text column in report painter?Please advice.
    Thank you.
    Regards,
    Karen
    Edited by: Karen Swee Ping Ho on Jun 17, 2011 2:48 AM

    Hi,
    Thank you for the promt reply.
    1) How I include the variable in the column header to display fiscal year which I have selected from the selection screen?
    which variable should i use?
    2) Where can i find more information about the characteristic and which variable to be use base on the characteristic?
    For example: I would like to display the fiscal year from the selection screen/input screen when execute the report which also will reflected to the element definition and will display the fiscal year also in the column text?
    3) Kindly advise base on question 2, the variable that i use in element definition it will also display  in selection screen?
    4) When execute the report the first selection screen input parameter it obtain from where it is from element definition?
    5) Please advice how to be done when report execute with first screen input selection will also reflect the element definition of column and rom with the selection of the fiscal year?
    Please help.
    many thanks
    Edited by: KH on Jun 18, 2011 7:18 AM

  • How to include field in document header

    Dear All,
    Any one please give me some input on how to include a field in document header of f-02 .
    Thanks,
    Srini.

    Hi,
    You will have to modify the screen via SE51 (program SAPMF05A, screen 100). Ask to your ABAP team to help you, though such a modification should be carefully considered.
    By the way, is it a user-defined field or field that should be there and is just missing? If the last is true, it could be a bug and solved by relevant OSS correction.
    Regards,
    Eli

  • How to include ratings in contact sheets in Bridge CS4??

    I'm trying to find out how to include my ratings and labels in a contact sheet, to share that with someone who is not going to use Bridge but ideally just a PDF. Is that at all possible? Thanks!

    Is that at all possible?
    To my knowledge not in the AOM settings, the options inhere are still a bit limited. But you can use the sort order for rating and in combination with batch rename you could be a bit creative by adding a mark like 1 star or 2 stars to the filename for the selected files. Or use same rated files per page.

  • How to include custom application.xml in JDev9i project

    Can anybody explain to me how to include a custom application.xml file when deploying to an .ear file? I need to include application wide security roles, and I can't see where in Jev9i how to do this.
    After searching this forum, I see that jdev9i can't include the orion-application.xml, but I want to include just the standard J2EE application.xml. Is this possible?
    Thanks,
    matt

    The standard application.xml file unfortunately can't be customized in JDev 9.0.2. The reasons why this capability was left out of JDev 9.0.2 are same reasons why the other EAR-level XML files were excluded. The OTN thread
    Re: Regarding 11i and E-business suite
    has a summary of those reasons, which you've probably seen. We know this is an area in need of improvement and will be adding this functionality in the JDev 9.0.3 release. Until then, you'll have to go with a work-around like an Ant build file, batch file, Java application, or some other kind of script.
    Below is a sample Java application which can be used to insert <security-role> elements into an EAR file's application.xml. Modify the main() method to customize for your purposes, and put xmlparserv2.jar on the classpath (in a JDev project, add the "Oracle XML Parser v2" library):
    package mypackage4;
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    import oracle.xml.parser.v2.*;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    public class PostProcessEAR
    public static void main( String[] args ) throws IOException
    final String earFile = "C:\\temp\\myapp.ear";
    final PostProcessEAR postProcess = new PostProcessEAR( earFile );
    postProcess.addSecurityRole( null, "first_role" );
    postProcess.addSecurityRole( "Description for the second role", "second_role" );
    postProcess.commit();
    System.out.println( "Done." );
    private final File _earFile;
    private final ArrayList _securityRoles = new ArrayList();
    public PostProcessEAR( String earFile )
    _earFile = new File( earFile );
    public void addSecurityRole( String description, String roleName )
    if ( roleName == null )
    throw new IllegalArgumentException();
    _securityRoles.add( description );
    _securityRoles.add( roleName );
    * Write out modified EAR file.
    public void commit() throws IOException
    if ( _securityRoles.size() == 0 )
    return;
    final ZipFile zipFile = new ZipFile( _earFile );
    final Enumeration entries = zipFile.entries();
    final File outFile = new File( _earFile.getAbsolutePath() + ".out" );
    final ZipOutputStream out = new ZipOutputStream( new BufferedOutputStream( new FileOutputStream( outFile ) ) );
    while ( entries.hasMoreElements() )
    final ZipEntry entry = (ZipEntry) entries.nextElement();
    final InputStream in = zipFile.getInputStream( entry );
    if ( "META-INF/application.xml".equals( entry.getName() ) )
    final XMLDocument modifiedApplicationXml = insertSecurityRoles( in );
    final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
    modifiedApplicationXml.print( byteOutput );
    final int numBytes = byteOutput.size();
    entry.setSize( numBytes );
    if ( entry.getMethod() == ZipEntry.STORED )
    entry.setCompressedSize( numBytes );
    final CRC32 crc32 = new CRC32();
    crc32.update( byteOutput.toByteArray() );
    entry.setCrc( crc32.getValue() );
    out.putNextEntry( entry );
    byteOutput.writeTo( out );
    else
    // Copy all other zip entries as they are.
    out.putNextEntry( entry );
    copy( in, out );
    in.close();
    out.close();
    private XMLDocument insertSecurityRoles( InputStream in ) throws IOException
    final DOMParser domParser = new DOMParser();
    domParser.setAttribute( DOMParser.STANDALONE, Boolean.TRUE );
    try
    domParser.parse( in );
    final XMLDocument doc = domParser.getDocument();
    final Element docElem = doc.getDocumentElement();
    final Iterator iter = _securityRoles.iterator();
    while ( iter.hasNext() )
    final String desc = (String) iter.next(); // might be null
    final String roleName = iter.next().toString(); // must not be null
    final Element securityRoleElem = doc.createElement( "security-role" );
    if ( desc != null )
    securityRoleElem.appendChild( createPcdata( doc, "description", desc ) );
    securityRoleElem.appendChild( createPcdata( doc, "role-name", roleName ) );
    docElem.appendChild( securityRoleElem );
    return doc;
    catch ( SAXException e )
    e.printStackTrace();
    return null;
    private Element createPcdata( XMLDocument doc, String elemName, String pcdata )
    final Element elem = doc.createElement( elemName );
    elem.appendChild( doc.createTextNode( pcdata ) );
    return elem;
    private final byte[] buffer = new byte[4096];
    private void copy( InputStream in, OutputStream out ) throws IOException
    while ( true )
    final int bytesRead = in.read( buffer );
    if ( bytesRead < 0 )
    break;
    out.write( buffer, 0, bytesRead );

  • How to include 0STOCK_VAL in a Query based on APO DataSource?

    Hi All,
    I have a requirement to include *0STOCK_VAL" from Inventory to the APO InfoCube. But the problem with this is, this particular KeyFigure is not present in the APO hence it cannot be included in the APO DataSource i.e. we cannot get this from the Source System.
    I checked the Production system, 0STOCK_VAL InfoObject is avaiable in one of the InfoCube but it is not present in any DSO's. Since it is not present in any of the DSO's we cannot write a Routine to read it from any of the table.
    I even thought of including the InfoCube where 0STOCK_VAL is present into a MultiProvider along with the APO InfoCube. I can define the joining condition based on Plant and Material. But if I drill down any other characteristics which are not common in both the  InfoCube then we will have a blank line in the Query which is not recommended.
    But this KeyFigure is very much needed in the Query.
    My question is how to include this in the APO InfoCube or How to get this in the Query with values??
    Can anybody please help me on this.
    Thanks in advance.
    Prasapbi

    hi Matt,
      In your example like a transaction was paid for with a payment type of PTAM, then you need all the transaction details. I suppose that all the required transaction details along with payment type PTAM will be loaded into an infoprovider and you run a report on top of this infoprovider. Then for that report you need to have a selection screen variable for Payment Type and if the user enters the payment type PTAM, then he can get all the other transaction details from the infoprovider.
    Let me know if i don't understand the requirement correctly.
    Hope it helps....

  • How to include md5 package in application

    Hi All,
    First of all sorry I posted in another users thread. In the thread http://forums.sun.com/thread.jspa?threadID=5426671 the person used org.bouncycastle.crypto.digests.MD5Digest for doing md5.
    I need some help here on how you include the org.bouncycastle.crypto.digests.MD5Digest library in my java code as I want to use the md5.
    I am also working on something similar like that but without the web application part and a detail which consists on OTP part using md5.
    As the md5() doesn't work in j2me so was also searching for something which will work on MIDP.
    package com.abc; //package define
    public class messDig5 //class define
        private String generateHash(String OTP, int loopNum) {
            byte[] secretBytes = OTP.getBytes();
            for (int x = 0; x < loopNum; x++) {
                byte[] tempStore = new byte[16];
                tempStore = hash(secretBytes);
                secretBytes = tempStore;
         //   return convertToHex(secretBytes);
            return byteArrayToHexString(secretBytes);
        public byte[] hash(byte[] secretBytes) {
           org.bouncycastle.crypto.digests.MD5Digest digest = new org.bouncycastle.crypto.digests.MD5Digest();
            digest.reset();
            // Update MD5 digest with user secret in byte format
            digest.update(secretBytes, 0, secretBytes.length);
            // get length of digest to initialise new md5 byte array
            int length = digest.getDigestSize();
            // create md5 byte array using length
            byte[] md5 = new byte[length];
            // calculate MD5 hash, using md5 byte array, 0 for buffer offset
            digest.doFinal(md5, 0);
            return md5;
    //    private static String convertToHex(byte[] data) {
    //        StringBuffer buf = new StringBuffer();
    //        String Hex;
    //        String formattedHex;
    //        for (int i = 0; i < data.length; i++) {
    //            int halfbyte = (data[i] >>> 4) & 0x0F;
    //            int two_halfs = 0;
    //            do {
    //                if ((0 <= halfbyte) && (halfbyte <= 9)) {
    //                    buf.append((char) ('0' + halfbyte));
    //                } else {
    //                    buf.append((char) ('a' + (halfbyte - 10)));
    //                halfbyte = data[i] & 0x0F;
    //            } while (two_halfs++ < 1);
    //        Hex = buf.toString();
    //        formattedHex = "\n" + Hex.substring(0, 4) + " " + Hex.substring(4, 8) + " " + Hex.substring(8, 12) + " " + Hex.substring(12, 16) + " " + Hex.substring(16, 20) + " " + Hex.substring(20, 24) + " " + Hex.substring(24, 28) + " " + Hex.substring(28, 32);
    //        return formattedHex;
        static String byteArrayToHexString(byte byteValues[]) {
            byte singleChar = 0;
            if (byteValues == null || byteValues.length <= 0) {
                return null;
            String entries[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "a", "b", "c", "d", "e", "f"};
            StringBuffer out = new StringBuffer(byteValues.length * 2);
            for (int i = 0; i < byteValues.length; i++) {
                singleChar = (byte) (byteValues[i] & 0xF0);
                singleChar = (byte) (singleChar >>> 4);
                // shift the bits down
                singleChar = (byte) (singleChar & 0x0F);
                out.append(entries[(int) singleChar]);
                singleChar = (byte) (byteValues[i] & 0x0F);
                out.append(entries[(int) singleChar]);
            String rslt = new String(out);
            return rslt;

    Camellia,
    I take you already added bouncycatsle to your project as a compile dependency, since it compiles (unless it does not).
    All you have to do for your code to work on the phone, you need to build your JAR file (that you use to distribute your MIDlet) with bouncycastle packaged in. This will all depend on the method you use to build your JAD and JAR files.
    I use antenna tool, which provides me with ant tasks to compile, build jar, package external libraries etc. Your scenario can be different, but all you have to do is to search manuals and/or google for methods on how to package external libraries with your build.
    Daniel

  • How to include user_sequences in a dbms_datapump procedure

    how to include user_sequences in a dbms_datapump procedure
    hi,
    i have a procedure to move all tables from MYSCHEMA_1 to MYSCHEMA_2 over a db_link
    using dbms_datapump ;
    That works fine
    but i need to copy the user_ sequences too.
    a detail if my procedure looks like this :
    ## create Job in TABLE-Mode :
    job_handle := dbms_datapump.open (
         operation      => 'IMPORT'
    ,job_mode => 'TABLE'
    ,remote_link           => p_database_link
    ,job_name      => vjob_name
    ## exclude same Tables:     
    dbms_datapump.metadata_filter (
         handle          =>     job_handle,
         name          =>     'NAME_EXPR',
         value          =>     'NOT IN (''TABLE_EXC_1'', ''TABLE_EXC_2'' , ''TABLE_EXC_3'' )'
    I found this to work with plain EXPDB :
    EXPDB INCLUDE=SEQUENCE: in ('SEQ','SEQ2') INCLUDE=TABLE: in ('TABLE','TABLE2')
    How to include user_sequences when working with dbms_datapump - API,
    maybe working with dbms_datapump.metadata_filter ?

    HI,
    you are right,
    to include SEQUENCES and other Objects like VIEW or FUNCTION
    does only work in SCHEMA-Mode
    But the next problem is
    when want to refresh the dump
    I can refresh the tables only
    dbms_datapump.set_parameter(
    handle      => job_handle,
    name      => 'TABLE_EXISTS_ACTION',
    value      => 'REPLACE'
    not the other objects like SEQUENCE or FUNCTION
    found in OracleSupport Note 1323411.1
    would nice to have a parameter OBJECT_EXISTS_ACTION in future

Maybe you are looking for

  • Conversion of multiple xml idocs to flat file

    Hi, I did ABAP mapping to convert xml idoc to flat file by using the reference how to do abap mapping in xi3.0.pdf It is working for only one idoc at a time. If I have multiple idocs in a single xml file, the above code is not working. Please let me

  • Please help me find TCP/IP in X

    Hello to the mac family, This posr is about my 350 slot load. I have installed Jag beside 9.2. No partition. Well I have finallydone it. I upgraded to Jag and got DSL. I connect fine using ethernet and Safari. What I want to do is make my system 9.2

  • Permission Denied error when attempting NW2004s Testdrive on SUSE Linux

    1) I downloaded the 7 .iso images for NW2004s testdrive and concatenated the files as described in the download page. 2) I wrote an image of the concatenated file onto a DVD. 3) Installed the 64 bit 1.4.2 JRE SLES 11 installation media. Had to "searc

  • Usage of BufferedInputStream & OutputStream#flush()

    I have a snippet below. InputStream fileInputStream = formFile.getInputStream();//org.apache.struts.upload.FormFile OutputStream out = = new BufferedOutputStream(new FileOutputStream(tempFilePath)); byte[] buffer = new byte[256 * 1024]; int contentLe

  • Won't Remember Window Placement

    I have a late 2010 MBA running up-to-date Mavericks with an external large display.  Since upgrading to Mavericks, when I move a Calendar, Contacts, Word or Skype windows to my small screen and restart the applications it places each window back on m