Example #1
0
def init_modules():
    global modules, pagehandlers

    cleanup_already_imported_modules()

    modules = []
    pagehandlers = {}

    module_names_prev = set(imports())

    # The config module is handled separate from the other modules
    module_names_prev.add("config")

    # Load the list of internal hard coded modules
    for module_name in internal_module_names:
        # TODO: use __import__
        modules.append(import_module(module_name))

    # Load all multisite pages which will also perform imports of the needed modules
    load_web_plugins('pages', globals())

    # Save the modules loaded during the former steps in the modules list
    modules += [
        globals()[m] for m in set(imports()).difference(module_names_prev)
    ]
Example #2
0
def handler(req):

    options = req.get_options()

    ## Process wsgi.base_uri

    base_uri = options.get('wsgi.base_uri', '')

    if base_uri == '/' or base_uri.endswith('/'):
        req.log_error(
            "WSGI handler: wsgi.base_uri (%s) must not be '/' or end with '/', declining."
            % `base_uri`, apache.APLOG_WARNING)
        return apache.DECLINED

    if req.uri.startswith(base_uri):
        req.path_info = req.uri[len(base_uri):]
    else:
        req.log_error(
            "WSGI handler: req.uri (%s) does not start with wsgi.base_uri (%s), declining."
            % (`req.uri`, `base_uri`), apache.APLOG_WARNING)
        return apache.DECLINED

    ## Find the application callable

    app = None
    app_str = options.get('wsgi.application')
    if app_str:
        mod_str, callable_str = (app_str.split('::', 1) + [None])[0:2]
        module = apache.import_module(mod_str, log=True)
        app = getattr(module, callable_str or 'application')

    if not app:
        req.log_error(
            'WSGI handler: wsgi.application (%s) not found, declining.'
            % `app_str`, apache.APLOG_WARNING)
        return apache.DECLINED

    ## Build env

    req.add_cgi_vars()
    env = dict(req.subprocess_env)

    if req.headers_in.has_key("authorization"):
        env["HTTP_AUTHORIZATION"] = req.headers_in["authorization"]

    env['wsgi.input'] = req
    env['wsgi.errors'] = sys.stderr
    env['wsgi.version'] = (1, 0)
    env['wsgi.multithread']  = apache.mpm_query(apache.AP_MPMQ_IS_THREADED)
    env['wsgi.multiprocess'] = apache.mpm_query(apache.AP_MPMQ_IS_FORKED)
    if env.get('HTTPS', 'off') == 'off':
        env['wsgi.url_scheme'] = 'http'
    else:
        env['wsgi.url_scheme'] = 'https'

    ## Run the app

    WSGIContainer(req).run(app, env)

    return apache.OK
Example #3
0
def post_processing():
    from mod_python import apache
    import global_variables as g

    page_template = apache.import_module(
        g.g_page.get_page_template(),
        path=[g.g_main_path + '/scripts/page_templates/'])
    g.g_content.setContent(page_template.generate_page())
Example #4
0
def handler(req):

    options = req.get_options()

    ## Find the application callable

    app = None
    app_str = options['mod_python.wsgi.application']
    if app_str:
        if '::' in app_str:
            mod_str, callable_str = app_str.split('::', 1)
        else:
            mod_str, callable_str = app_str, 'application'
        config = req.get_config()
        autoreload, log = True, False
        if "PythonAutoReload" in config:
            autoreload = config["PythonAutoReload"] == "1"
        if "PythonDebug" in config:
            log = config["PythonDebug"] == "1"
        module = apache.import_module(mod_str, autoreload=autoreload, log=log)

        try:
            app = module.__dict__[callable_str]
        except KeyError:
            pass

    if not app:
        req.log_error(
            'WSGI handler: mod_python.wsgi.application (%s) not found, declining.'
            % repr(app_str), apache.APLOG_WARNING)
        return apache.DECLINED

    ## Build env

    env = req.build_wsgi_env()
    if env is None:
        # None means base_uri mismatch. The problem can be either
        # base_uri or Location, but because we couldn't be here if it
        # was Location, then it must be mod_python.wsgi.base_uri.
        base_uri = options.get('mod_python.wsgi.base_uri')
        req.log_error(
            "WSGI handler: req.uri (%s) does not start with mod_python.wsgi.base_uri (%s), declining."
            % (repr(req.uri), repr(base_uri)), apache.APLOG_WARNING)
        return apache.DECLINED

    ## Run the app

    response = None
    try:
        response = app(env, req.wsgi_start_response)
        [req.write(token) for token in response]
    finally:
        # call close() if there is one
        if type(response) not in (list, tuple):
            getattr(response, 'close', lambda: None)()

    return apache.OK
Example #5
0
def handler(req):

    options = req.get_options()

    ## Find the application callable

    app = None
    app_str = options['mod_python.wsgi.application']
    if app_str:
        if '::' in app_str:
            mod_str, callable_str = app_str.split('::', 1)
        else:
            mod_str, callable_str = app_str, 'application'
        config = req.get_config()
        autoreload, log = True, False
        if "PythonAutoReload" in config:
            autoreload = config["PythonAutoReload"] == "1"
        if "PythonDebug" in config:
            log = config["PythonDebug"] == "1"
        module = apache.import_module(mod_str, autoreload=autoreload, log=log)

        try:
            app = module.__dict__[callable_str]
        except KeyError: pass

    if not app:
        req.log_error(
            'WSGI handler: mod_python.wsgi.application (%s) not found, declining.'
            % repr(app_str), apache.APLOG_WARNING)
        return apache.DECLINED

    ## Build env

    env = req.build_wsgi_env()
    if env is None:
        # None means base_uri mismatch. The problem can be either
        # base_uri or Location, but because we couldn't be here if it
        # was Location, then it must be mod_python.wsgi.base_uri.
        base_uri = options.get('mod_python.wsgi.base_uri')
        req.log_error(
            "WSGI handler: req.uri (%s) does not start with mod_python.wsgi.base_uri (%s), declining."
            % (repr(req.uri), repr(base_uri)), apache.APLOG_WARNING)
        return apache.DECLINED

    ## Run the app

    response = None
    try:
        response = app(env, req.wsgi_start_response)
        [req.write(token) for token in response]
    finally:
        # call close() if there is one
        if type(response) not in (list, tuple):
            getattr(response, 'close', lambda: None)()

    return apache.OK
Example #6
0
def handler(req):
  path, module_name = os.path.split(req.filename)
  module_name, module_ext = os.path.splitext(module_name)
  # Let it be 500 Internal Server Error in case of import error
  module = apache.import_module(module_name, path=[path])

  req.add_common_vars()
  module.index(req)

  return apache.OK
def process_page():
	from mod_python import apache

	page = apache.import_module(global_variables.g_page_name, path=[global_variables.g_main_path + '/scripts/pages/'])
	page.page_additions()
	global_variables.g_content.setTitle(page.get_title())
	global_variables.g_content.setContent(page.get_content())
	global_variables.g_content.setPageTemplate(page.get_page_template())

	global_variables.g_page = page
Example #8
0
def handler(req):
    path, module_name = os.path.split(req.filename)
    module_name, module_ext = os.path.splitext(module_name)
    try:
        module = apache.import_module(module_name, path=[path])
    except ImportError:
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    req.add_common_vars()
    module.index(req)

    return apache.OK
Example #9
0
def process_page():
    from mod_python import apache

    page = apache.import_module(
        global_variables.g_page_name,
        path=[global_variables.g_main_path + '/scripts/pages/'])
    page.page_additions()
    global_variables.g_content.setTitle(page.get_title())
    global_variables.g_content.setContent(page.get_content())
    global_variables.g_content.setPageTemplate(page.get_page_template())

    global_variables.g_page = page
Example #10
0
def handler(req):
    path, module_name = os.path.split(req.filename)
    module_name, module_ext = os.path.splitext(module_name)
    try:
        module = apache.import_module(module_name, path=[path])
    except ImportError:
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    req.add_common_vars()
    module.index(req)

    return apache.OK
Example #11
0
def getFile(req, lat, long, year):
    monthly = False
    if year == "All":
        year =  datetime.now().strftime("%Y")
        monthly = True

    #lat = "36.825"
    #long = "-98.0525"
    dir = "/srv/www/python.davidlary.info/public_html/"
    if monthly:
        filename = dir + "csv/" + lat + long + '.csv'
        filenameSend = "csv/" + lat + long + '.csv'
    else:
        filename = dir + "csv/" + lat + long + year+ '.csv'
        filenameSend = "csv/" + lat + long + year + '.csv'

    os.chdir(dir)
    apache.import_module("sys")
    logging.basicConfig(filename="../cgi-bin/logs/csvCreator"+str(datetime.now()).replace(" ", ""), level=logging.DEBUG)
    stdout_logger = logging.getLogger('STDOUT')
    sl = scriptOne.StreamToLogger(stdout_logger, logging.INFO)
    sys.stdout = sl

    stderr_logger = logging.getLogger('STDERR')
    sl = scriptOne.StreamToLogger(stderr_logger, logging.ERROR)
    sys.stderr = sl
    print "test"
    #os.chdir('~')
    if not os.path.exists(filename):
        if monthly:
            scriptOne.scriptOne( ['script name', lat, long, filename,'-s', '2003-01-01', '-e', year + '-12-12', '-m'])
        else:
            scriptOne.scriptOne( ['script name', lat, long, filename,'-s', year + '-01-01', '-e', year + '-12-12', '-m'])

    #open('output.csv', 'w')
    req.content_type = 'text/javascript'
	#req.write('<body>')
	#req.write('<br>Time series for your location.<br>')
    req.write(json.dumps(filenameSend))
Example #12
0
def link(fname):
	global cale
	
	color = apache.import_module('color', path = [cale])
	usedb = apache.import_module('usedb', path = [cale])
	
	toks = []
	try:
		f = open(fname, 'r')
		toks = color.tokenize(f.read())
		f.close()
	except:
		return prnt(fname)

	db = os.path.join(cale, 'newdb')

	s  = '<html> <body>' 

	for tok in toks:
		entry = []
		try:
			entry = usedb.search(db, tok)
		except sqlite3.Error,msg:
			prnt(msg)
			
		if tok == '\n':
			s += '<br />'
		elif tok == '<':
			s += '&lt;'
		elif tok == '\t':
			for x in range(8):
				s += '&nbsp;'
		elif len(entry) > 0:
			s += '<a href ="link?fname=%s"> %s </a>' \
				% (entry[0][0].encode(),tok)
		else:
			s += tok 
Example #13
0
def do_dir(req, config, proj, path):
	""" Does the stuff needed for a directory (when we have a "?d=..." GET directive). """
	
	import_dir = os.path.join(os.path.dirname(__file__), "dbaccess")
	dbsearch = apache.import_module('dbsearch', path=[import_dir])

	db_filename = config.get(proj, "db-file")
	DB = dbsearch.DBSearch(db_filename)
	content = DB.searchFile(path+"%")

	web_url = config.get('root', 'web-url')

	# Get the parent of the current path and output it
	parent = '/'.join(path.split('/')[:-1])
	if parent == '/':
		parent = '' # don't ask me why ...

	DEBUG = None
	listing = []
	if content is None:
		DEBUG = ['Forbidden? Or unavailable? Or even inexistent... IDK!']
	else:
		content.sort(key = lambda (x,y,z,t): (t,x))
		# Hardcoding insertion of '.' and '..' in listing
		listing = [{'type':'dir', 'link':path, 'display':'.'}, {'type':'dir', 'link':parent, 'display':'..'}]
		for (f, s, d, t) in content:
			father = re.search("^(.*)/*(.*)/",f).group(0)[:-1]
			if path != father:
				continue
			e = f[::-1]
			e = re.search("[a-zA-Z_\-0-9\.]+/", e).group(0)
			e = e[::-1]
			if t == 'dir':
				listing.append( {'type':'dir', 'link':f, 'display':e} )
			elif t=='reg':
				listing.append( {'type':'reg', 'link':f, 'display':e, 'size':s, 'date':datetime.fromtimestamp(d)} )
			else:
				listing.append( {'type':'n/a', 'display':e} )

	req.content_type = 'html'
	tmpl = psp.PSP(req, filename='web/templates/dirlist.tmpl')
	tmpl.run( vars={
			'web_url':web_url,
			'proj': proj,
			'DEBUG': DEBUG,
			'listing': listing,
			'dirpath': path
			})
Example #14
0
def load_extension(ext_name, configs = []):
    """Load extension by name, then return the module.

    The extension name may contain arguments as part of the string in the
    following format: "extname(key1=value1,key2=value2)"

    """

    # Parse extensions config params (ignore the order)
    configs = dict(configs)
    pos = ext_name.find("(") # find the first "("
    if pos > 0:
        ext_args = ext_name[pos+1:-1]
        ext_name = ext_name[:pos]
        pairs = [x.split("=") for x in ext_args.split(",")]
        configs.update([(x.strip(), y.strip()) for (x, y) in pairs])

    # Setup the module names
    ext_module = 'markdown.extensions'
    module_name_new_style = '.'.join([ext_module, ext_name])
    module_name_old_style = '_'.join(['mdx', ext_name])

    extensions = [os.path.dirname(__file__) + '/extensions']
    module = apache.import_module(ext_name, path=extensions)

    """
    # Try loading the extention first from one place, then another
    try: # New style (markdown.extensons.<extension>)
        module = __import__(module_name_new_style, {}, {}, [ext_module])
    except ImportError:
        try: # Old style (mdx.<extension>)
            module = __import__(module_name_old_style)
        except ImportError:
           message(WARN, "Failed loading extension '%s' from '%s' or '%s'"
               % (ext_name, module_name_new_style, module_name_old_style))
           # Return None so we don't try to initiate none-existant extension
           return None
    """

    # If the module is loaded successfully, we expect it to define a
    # function called makeExtension()
    try:
        return module.makeExtension(configs.items())
    except AttributeError:
        message(CRITICAL, "Failed to initiate extension '%s'" % ext_name)
Example #15
0
def init_modules():
    global modules      ; modules = []
    global pagehandlers ; pagehandlers = {}

    module_names_prev = set(imports())

    # The config module is handled separate from the other modulesa
    module_names_prev.add("config")

    # Load the list of internal hard coded modules
    for module_name in internal_module_names:
        # FIXME: use __import__
        modules.append(import_module(module_name))

    # Load all multisite pages which will also perform imports of the needed modules
    load_web_plugins('pages', globals())

    # Save the modules loaded during the former steps in the modules list
    modules += [ globals()[m] for m in set(imports()).difference(module_names_prev) ]
Example #16
0
def handler(req):
    InstDB.DebugReq = req

    init(req)

    req.content_type = "text/html"

    dlfile = "download.py"

    # Was download.py specified?
    if req.filename[-len(dlfile):] == dlfile:
        action = "dnld"
    else:
        action = InstDB.Fields.get("Action", None)

    # Invalidate the session if user requested logout
    if action == "logout" and InstDB.User:
        InstDB.Sess.invalidate()
        InstDB.User = None
        InstDB.Sess["UserId"] = 0

        # Redirect to home page
        if req.proto_num >= 1001:
            req.status = apache.HTTP_TEMPORARY_REDIRECT
        else:
            req.status = apache.HTTP_MOVED_TEMPORARILY

        req.headers_out["Location"] = "patches.py"
        req.send_http_header()
        return apache.OK
    elif action not in ("browse", "list", "item", "edit", "search", "register",
                        "dnld", "submit", "software", "help", "profile",
                        "resetpass", "confirm", "dbinit", "emailnews",
                        "md5find"):
        action = "index"

    mod = apache.import_module(action)
    mod.action(req, InstDB.Fields)

    shutdown()

    return apache.OK
Example #17
0
def do_file(req, config, proj, path, tag):
	""" Will pass the file to the lexer, and then the structure will be returned to the server page and processed there. """

	directory = os.path.join(os.path.dirname(__file__), "lexer/")
	Lexer = apache.import_module('lexer', path=[directory])
	
	fullpath = os.path.join(config.get(proj, 'src-dir'), path[1:])
	lexer = Lexer.Lexer(fullpath, config.get(proj, 'db-file'))

	web_url = config.get('root','web-url')
	
	req.content_type = 'html'
	tmpl = psp.PSP(req, filename='web/templates/source.tmpl')
	tmpl.run( vars = {
			'tag':tag,
			'web_url':web_url,
			'proj': proj,
			'filename': path,
			'lines':lexer.get()
			})
Example #18
0
def search(req):
	try:
		search = req.form['tag']
		proj = req.form['proj']
		
		config = parse_config()
		dbfile = config.get(proj, 'db-file')
		xafile = config.get(proj, 'xapian-dir')
		
		directory = os.path.join(os.path.dirname(__file__), "dbaccess/")
		dbsearch = apache.import_module('dbsearch', path=[directory])
		# xapian = apache.import_module('xapianSearch', path=[directory])
		DBS = dbsearch.DBSearch(dbfile)

		allTags = DBS.searchTag(search, '', allMatches=True)
		if allTags is not None:
			allTags.sort(key = lambda (a,b,c): (c,a,b))

		matchingFiles = DBS.searchFile('%'+search+'%')
			
		# allMatches = xapian.search(xafile, search)
		params = urllib.urlencode({'config':xafile, 'search':search})
		web_url = config.get('root', 'web-url')
		p = urllib.urlopen("%s/workaround.php?%s" % (web_url,params))
		allMatches = eval(p.read())
		if allMatches is not None:
			allMatches.sort()

		req.content_type = 'html'
		tmpl = psp.PSP(req, filename='web/templates/search.tmpl')
		tmpl.run( vars = {
				'proj':proj,
				'allTags':allTags,
				'allMatches':allMatches,
				'search':search,
				'web_url':web_url,
				'allFiles':matchingFiles
				})
	except Exception, ex:
		return str(ex)
		index(req)
Example #19
0
    def findServiceEndpoint(self, name):
        req = self.req

        (modulePath, fileName) = os.path.split(req.filename)
        (moduleName, ext) = os.path.splitext(fileName)
        
        if not os.path.exists(os.path.join(modulePath, moduleName + ".py")):
            raise ServiceImplementaionNotFound()
        else:
            if not modulePath in sys.path:
                sys.path.insert(0, modulePath)

            from mod_python import apache
            module = apache.import_module(moduleName, log=1)
            
            if hasattr(module, "service"):
                self.service = module.service
            elif hasattr(module, "Service"):
                self.service = module.Service()
            else:
                self.service = module

        return ServiceHandler.findServiceEndpoint(self, name)
Example #20
0
    def findServiceEndpoint(self, name):
        req = self.req

        (modulePath, fileName) = os.path.split(req.filename)
        (moduleName, ext) = os.path.splitext(fileName)

        if not os.path.exists(os.path.join(modulePath, moduleName + ".py")):
            raise ServiceImplementaionNotFound()
        else:
            if not modulePath in sys.path:
                sys.path.insert(0, modulePath)

            from mod_python import apache
            module = apache.import_module(moduleName, log=1)

            if hasattr(module, "service"):
                self.service = module.service
            elif hasattr(module, "Service"):
                self.service = module.Service()
            else:
                self.service = module

        return ServiceHandler.findServiceEndpoint(self, name)
Example #21
0
    def find_service_method(self, name):
        req = self.req

        (path, filename) = os.path.split(req.filename)
        (module, ext) = os.path.splitext(filename)

        if not os.path.exists(os.path.join(path, module + '.py')):
            raise ServiceMethodNotFound()
        else:
            if not path in sys.path:
                sys.path.insert(1, path)

            from mod_python import apache
            module = apache.import_module(module, log=1)

            if hasattr(module, 'service'):
                self.service = module.service
            elif hasattr(module, 'Service'):
                self.service = module.Service()
            else:
                self.service = module

        return super(ModPyServiceHandler, self).find_service_method(name)
Example #22
0
def handler(req):
    (modulePath, fileName) = os.path.split(req.filename)
    (moduleName, ext) = os.path.splitext(fileName)

    if not os.path.exists(os.path.join(modulePath, moduleName + ".py")):
        return apache.HTTP_NOT_FOUND

    if not modulePath in sys.path:
        sys.path.insert(0, modulePath)

    module = apache.import_module(moduleName, log=1)

    if hasattr(module, "getService"):
        service = module.getService()
    elif hasattr(module, "service"):
        service = module.service
    elif hasattr(module, "Service"):
        service = module.Service()
    else:
        return apache.HTTP_SERVICE_UNAVAILABLE

    ModPyHandler(service, messageDelimiter="\n").handle(req)

    return apache.OK
Example #23
0
    def find_service_method(self, name):
        req = self.req

        (path, filename) = os.path.split(req.filename)
        (module, ext) = os.path.splitext(filename)

        if not os.path.exists(os.path.join(path, module + ".py")):
            raise ServiceMethodNotFound()
        else:
            if not path in sys.path:
                sys.path.insert(1, path)

            from mod_python import apache

            module = apache.import_module(module, log=1)

            if hasattr(module, "service"):
                self.service = module.service
            elif hasattr(module, "Service"):
                self.service = module.Service()
            else:
                self.service = module

        return super(ModPyServiceHandler, self).find_service_method(name)
def handler(req):    
    (modulePath, fileName) = os.path.split(req.filename)
    (moduleName, ext) = os.path.splitext(fileName)
    
    if not os.path.exists(os.path.join(modulePath, moduleName + ".py")):
        return apache.HTTP_NOT_FOUND
        
    if not modulePath in sys.path:
        sys.path.insert(0, modulePath)
    
    module = apache.import_module(moduleName, log=1)
       
    if hasattr(module, "getService"):
        service = module.getService()
    elif hasattr(module, "service"):
        service = module.service
    elif hasattr(module, "Service"):
        service = module.Service()
    else:
        return apache.HTTP_SERVICE_UNAVAILABLE
    
    ModPyHandler(service, messageDelimiter="\n").handle(req)
    
    return apache.OK
Example #25
0
# Written 2007

__author__ = '[email protected] (Addie Beseda)'

""" Connects to the VimCommands/VimDates table and grabs today's command. """


from datetime import date

from mod_python import apache
import MySQLdb

#import vim_gadget_manipulator
# We have to handle this differently thanks to modpython!
vcg_path = '/home/demew/public_html/sandbox/python/'
vim_gadget_manipulator = apache.import_module('vim_gadget_manipulator',
                                              path=[vcg_path])

class GadgetGrabber(object):

  def __init__(self):
    """ Instantiates a GadgetGrabber object. """
    self.__db = MySQLdb.connect(user='******', passwd='xxxxxx', db='xxxxxx')
    self.__db_cursor = self.__db.cursor() # Execute on the cursor
    self.today = date.today()
    self.__gu = vim_gadget_manipulator.GadgetUpdater()  

  def GrabTodaysCommand(self):
    """ Grabs the command associated with today from the db.
  
    Returns:
      Tuple containing two strings: first representing command, second
Example #26
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from mod_python import util, apache
import uuid
import sqlite3
import shutil

import sys
reload(sys)
sys.setdefaultencoding('utf8')

__dir__ = os.path.dirname(__file__)
read_xmp = apache.import_module(os.path.join(__dir__, 'lib/read_xmp.py'))


def __store_file(fileDesc):
    # Generate UUID
    id = str(uuid.uuid4())
    # Temporary store file in filesystem
    f = open(os.path.join(__dir__, 'tmp/' + id), 'w')
    f.write(fileDesc.value)
    f.close()
    # Get Dublin Core properties from XMP
    props = read_xmp.get_dc_from_file(os.path.join(__dir__, 'tmp/' + id))
    # Fill properties with further knowledge
    if not 'format' in props.keys():
        props['format'] = fileDesc.type
    if not 'title' in props.keys():
        props['title'] = fileDesc.filename
Example #27
0
# Import Statements {{{

import cgi, os, random, re, string, sys, urllib2, uuid

from mod_python import apache, psp, Session, util

from datetime import datetime
from xml.sax import saxutils

try:
    import wikidiff2
except:
    wikidiff2 = None

cynfig = apache.import_module('~/cynfig.py')

library = [os.path.dirname(__file__) + '/library']

markdown = apache.import_module('markdown/__init__', path=library)
pytz = apache.import_module('pytz/__init__', path=library)
smartypants = apache.import_module('smartypants', path=library)

try:
    tidy = apache.import_module('tidy/__init__', path=library)
except OSError:
    tidy = None

try:
    markdown_extensions = cynfig.markdown_extensions
except AttributeError:
Example #28
0
from mod_python import apache

pinyin = apache.import_module('src/pinyin')
converter = pinyin.Converter()

def index(text, fmt = 'df', sc = 'true', pp = 'false', fuzzy = '0'):

    if sc == 'true':
        sc = True
    elif sc == 'false':
        sc = False
    else:
        sc = True

    if pp == 'true':
        pp = True
    elif pp == 'false':
        pp = False
    else:
        pp = False

    try:
        fuzzy = int(fuzzy)
    except ValueError:
        fuzzy = 0

    global converter
    return converter.convert(text, fmt, sc, pp, fuzzy)
Example #29
0
# COPYRIGHT 2004-2005 DUMPLETON SOFTWARE CONSULTING PTY LIMITED

from mod_python import apache
from mod_python import util

# We can't use the "import" statement for "publisher"
# because of strange problems in mod_python module
# loader. Namely, if "import" is used and PythonHandler
# is defined elsewhere as "mod_python.publisher" and it
# gets loaded before this code, the "publisher" module
# can not then be found. Instead use the mod_python
# module loader itself as then it always works.

#from mod_python import publisher
publisher = apache.import_module("mod_python.publisher")

import os
import types
import string
import re
import sys
import base64
import new
import inspect

import cache
import config
import forms

_moduleCache = cache.ModuleCache()
_configCache = config.ConfigCache()
Example #30
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from mod_python import util,apache
import uuid
import sqlite3
import shutil

import sys
reload(sys)
sys.setdefaultencoding('utf8')

__dir__         = os.path.dirname(__file__)
read_xmp = apache.import_module(os.path.join(__dir__, 'lib/read_xmp.py'))


def __store_file( fileDesc ):
	# Generate UUID
	id = str(uuid.uuid4())
	# Temporary store file in filesystem
	f = open( os.path.join(__dir__, 'tmp/' + id), 'w' )
	f.write( fileDesc.value )
	f.close()
	# Get Dublin Core properties from XMP
	props = read_xmp.get_dc_from_file( os.path.join(__dir__, 'tmp/' + id) )
	# Fill properties with further knowledge
	if not 'format' in props.keys():
		props['format'] = fileDesc.type
	if not 'title' in props.keys():
		props['title'] = fileDesc.filename
Example #31
0
         if the method is not defined, we return HTTP_NOT_IMPLEMENTED 
 """
 #Set log level here. For Production, disable both lines
 logging.basicConfig(
     level=logging.DEBUG
 )  #Used for debug, lot of data, not recommended for simple error search.
 #logging.basicConfig(level=logging.INFO) #Used for error search with config.
 # 1.
 try:
     (mtype, mid) = req.path_info.lstrip('/').split('/', 1)
 except ValueError, err:
     mtype = req.path_info.lstrip('/')
     mid = ''
 try:
     resourceModule = apache.import_module(mtype.strip('/').replace(
         '/', '.'),
                                           path=os.path.dirname(__file__))
 except Exception, err:
     if debug: raise
     return apache.HTTP_NOT_FOUND
 # 2.
 try:
     allowedMethodes = resourceModule.allowedMethodes
 except AttributeError, err:
     if debug: raise
     return apache.HTTP_HTTP_NOT_FOUND
 if not req.method in allowedMethodes:
     req.allow_methods(resourceModule.allowedMethodes, 1)
     return apache.HTTP_METHOD_NOT_ALLOWED
 # 3.
 if not 'form' in dir(req):
Example #32
0
def configure_handler(req, default):

    req.allow_methods(["GET", "POST"])
    if req.method not in ["GET", "POST"]:
        raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

    func_path = ""
    if req.path_info:
        func_path = req.path_info[1:]  # skip first /
        #func_path = func_path.replace("/", ".")
        #if func_path[-1:] == ".":
        #    func_path = func_path[:-1]
        # changed: only keep the first directory
        func_path = re.sub('/.*', '', func_path)

    # default to 'index' if no path_info was given
    if not func_path:
        func_path = "index"

    # if any part of the path begins with "_", abort
    if func_path[0] == '_' or func_path.count("._"):
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    ## import the script
    path, module_name = os.path.split(req.filename)
    if not module_name:
        module_name = "index"

    # get rid of the suffix
    #   explanation: Suffixes that will get stripped off
    #   are those that were specified as an argument to the
    #   AddHandler directive. Everything else will be considered
    #   a package.module rather than module.suffix
    exts = req.get_addhandler_exts()
    if not exts:
        # this is SetHandler, make an exception for Python suffixes
        exts = imp_suffixes
    if req.extension:  # this exists if we're running in a | .ext handler
        exts += req.extension[1:]
    if exts:
        suffixes = exts.strip().split()
        exp = "\\." + "$|\\.".join(suffixes)
        suff_matcher = re.compile(exp)  # python caches these, so its fast
        module_name = suff_matcher.sub("", module_name)

    # import module (or reload if needed)
    # the [path] argument tells import_module not to allow modules whose
    # full path is not in [path] or below.
    config = req.get_config()
    autoreload = int(config.get("PythonAutoReload", 1))
    log = int(config.get("PythonDebug", 0))
    try:
        module = apache.import_module(module_name,
                                      autoreload=autoreload,
                                      log=log,
                                      path=[path])
    except ImportError:
        et, ev, etb = sys.exc_info()
        # try again, using default module, perhaps this is a
        # /directory/function (as opposed to /directory/module/function)
        func_path = module_name
        module_name = "index"
        try:
            module = apache.import_module(module_name,
                                          autoreload=autoreload,
                                          log=log,
                                          path=[path])
        except ImportError:
            # raise the original exception
            raise et, ev, etb

    # does it have an __auth__?
    realm, user, passwd = process_auth(req, module)

    # resolve the object ('traverse')
    try:
        object = resolve_object(req, module, func_path, realm, user, passwd)
    except AttributeError:
        # changed, return the default path instead
        #raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
        object = default
    # not callable, a class or an unbound method
    if (not callable(object) or type(object) is ClassType
            or (hasattr(object, 'im_self') and not object.im_self)):

        result = str(object)

    else:
        # callable, (but not a class or unbound method)

        # process input, if any
        req.form = util.FieldStorage(req, keep_blank_values=1)

        result = util.apply_fs_data(object, req.form, req=req)

    if result or req.bytes_sent > 0 or req.next:

        if result is None:
            result = ""
        else:
            result = str(result)

        # unless content_type was manually set, we will attempt
        # to guess it
        if not req._content_type_set:
            # make an attempt to guess content-type
            if result[:100].strip()[:6].lower() == '<html>' \
               or result.find('</') > 0:
                req.content_type = 'text/html'
            else:
                req.content_type = 'text/plain'

        if req.method != "HEAD":
            req.write(result)
        else:
            req.write("")
        return apache.OK
    else:
        req.log_error("mod_python.publisher: %s returned nothing." %
                      ` object `)
        return apache.HTTP_INTERNAL_SERVER_ERROR
Example #33
0

#import cgi programs
import cgi
import cgitb

import os

#import database query script

from mod_python import apache


directory = os.path.dirname(_file_)

model = apache.import_module('models.py', path = [directory])

Gene = models.Gene([query])




cgitb.enable()


form = cgi.FieldStorage()
#write out the data that is to be output back to the webpage.

print "content-type: text/html" #html stuff is following
print
print "<html><head> <title> Your results </title></head>"
Example #34
0
from mod_python import apache
export = apache.import_module("fast_2012b_export")

class template:
    def __init__(self):
        self.export = export
        author = [{'name':'ProposalID',
                   'fieldname':'proposalid',
                   'fieldtype':'integer',
                   'section': False},
                  {'name' : 'Number',
                   'fieldname' : 'numb',
                   'fieldtype' : 'integer',
                   'section'   : 'author',
                   'shortname' : '#'},
                  {'name':'Name',
                   'fieldname':'name',
                   'fieldtype':'text',
                   'section':'author'},
                  {'name':'E-mail',
                   'fieldname':'email',
                   'fieldtype':'text',
                   'section':'author'},
                  {'name':'Phone',
                   'fieldname':'phone',
                   'fieldtype':'text',
                   'section':'author'},
                  {'name':'Institution',
                   'fieldname':'institution',
                   'fieldtype':'institution',
                   'section':'author'},
Example #35
0
def handler(req):

    # using a closure is faster than an object-based implementation
    def start_response(status, headers, exc_info=None):

        if exc_info:
            try:
                raise exc_info[0], exc_info[1], exc_info[2]
            finally:
                exc_info = None

        # avoid str2int conversion for frequently used ones
        if status == '200':
            req.status = 200
        elif status == '301':
            req.status = 301
        elif status == '302':
            req.status = 302
        else:
            req.status = int(status[:3])

        # There is no need to req.set_content_length() or set
        # req.content_type because it will be in the headers anyhow.
        for k,v in headers:
            req.headers_out.add(k,v)

        return req.write

    options = req.get_options()

    ## Find the application callable

    app = None
    app_str = options['mod_python.wsgi.application']
    if app_str:
        if '::' in app_str:
            mod_str, callable_str = app_str.split('::', 1)
        else:
            mod_str, callable_str = app_str, 'application'
        config = req.get_config()
        autoreload, log = True, False
        if "PythonAutoReload" in config:
            autoreload = config["PythonAutoReload"] == "1"
        if "PythonDebug" in config:
            log = config["PythonDebug"] == "1"
        module = apache.import_module(mod_str, autoreload=autoreload, log=log)

        try:
            app = module.__dict__[callable_str]
        except KeyError: pass

    if not app:
        req.log_error(
            'WSGI handler: mod_python.wsgi.application (%s) not found, declining.'
            % `app_str`, apache.APLOG_WARNING)
        return apache.DECLINED

    ## Build env

    env = req.build_wsgi_env()
    if env is None:
        # None means base_uri mismatch. The problem can be either
        # base_uri or Location, but because we couldn't be here if it
        # was Location, then it must be mod_python.wsgi.base_uri.
        base_uri = options.get('mod_python.wsgi.base_uri')
        req.log_error(
            "WSGI handler: req.uri (%s) does not start with mod_python.wsgi.base_uri (%s), declining."
            % (`req.uri`, `base_uri`), apache.APLOG_WARNING)
        return apache.DECLINED

    ## Run the app

    response = None
    try:
        response = app(env, start_response)
        [req.write(token) for token in response]
    finally:
        # call close() if there is one
        if type(response) not in (list, tuple):
            getattr(response, 'close', lambda: None)()

    return apache.OK
Example #36
0
import MySQLdb
import hashlib
import string
import operator
import os.path
import os
import gzip
from random import choice
from mod_python import apache
cpss = apache.import_module("cpss")

class Backend:
    def __init__(self):
        self.Database = MySQLdb.connect(
            host        = cpss.config['db']['host'], 
            user        = cpss.config['db']['user'],
            passwd      = cpss.config['db']['passwd'],
            db          = cpss.config['db']['db'],
            unix_socket = cpss.config['db']['unix_socket'])
        self.literal = self.Database.literal
        self.options = self.options_get()
        self.path_justification = (cpss.config['data_directory'] + 
                                   'justifications/')
        self.path_pdf = cpss.config['data_directory'] + 'pdf/'
        self.path_images = cpss.config['data_directory'] + 'images/'


    def verify_user(self, username, password):
        cursor = self.Database.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        response = cursor.execute("""SELECT * 
                                     FROM `users`
Example #37
0
def configure_handler(req, default):

    req.allow_methods(["GET", "POST"])
    if req.method not in ["GET", "POST"]:
        raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

    func_path = ""
    if req.path_info:
        func_path = req.path_info[1:]  # skip first /
        # func_path = func_path.replace("/", ".")
        # if func_path[-1:] == ".":
        #    func_path = func_path[:-1]
        # changed: only keep the first directory
        func_path = re.sub("/.*", "", func_path)

    # default to 'index' if no path_info was given
    if not func_path:
        func_path = "index"

    # if any part of the path begins with "_", abort
    if func_path[0] == "_" or func_path.count("._"):
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    ## import the script
    path, module_name = os.path.split(req.filename)
    if not module_name:
        module_name = "index"

    # get rid of the suffix
    #   explanation: Suffixes that will get stripped off
    #   are those that were specified as an argument to the
    #   AddHandler directive. Everything else will be considered
    #   a package.module rather than module.suffix
    exts = req.get_addhandler_exts()
    if not exts:
        # this is SetHandler, make an exception for Python suffixes
        exts = imp_suffixes
    if req.extension:  # this exists if we're running in a | .ext handler
        exts += req.extension[1:]
    if exts:
        suffixes = exts.strip().split()
        exp = "\\." + "$|\\.".join(suffixes)
        suff_matcher = re.compile(exp)  # python caches these, so its fast
        module_name = suff_matcher.sub("", module_name)

    # import module (or reload if needed)
    # the [path] argument tells import_module not to allow modules whose
    # full path is not in [path] or below.
    config = req.get_config()
    autoreload = int(config.get("PythonAutoReload", 1))
    log = int(config.get("PythonDebug", 0))
    try:
        module = apache.import_module(module_name, autoreload=autoreload, log=log, path=[path])
    except ImportError:
        et, ev, etb = sys.exc_info()
        # try again, using default module, perhaps this is a
        # /directory/function (as opposed to /directory/module/function)
        func_path = module_name
        module_name = "index"
        try:
            module = apache.import_module(module_name, autoreload=autoreload, log=log, path=[path])
        except ImportError:
            # raise the original exception
            raise et, ev, etb

    # does it have an __auth__?
    realm, user, passwd = process_auth(req, module)

    # resolve the object ('traverse')
    try:
        object = resolve_object(req, module, func_path, realm, user, passwd)
    except AttributeError:
        # changed, return the default path instead
        # raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
        object = default
    # not callable, a class or an unbound method
    if not callable(object) or type(object) is ClassType or (hasattr(object, "im_self") and not object.im_self):

        result = str(object)

    else:
        # callable, (but not a class or unbound method)

        # process input, if any
        req.form = util.FieldStorage(req, keep_blank_values=1)

        result = util.apply_fs_data(object, req.form, req=req)

    if result or req.bytes_sent > 0 or req.next:

        if result is None:
            result = ""
        else:
            result = str(result)

        # unless content_type was manually set, we will attempt
        # to guess it
        if not req._content_type_set:
            # make an attempt to guess content-type
            if result[:100].strip()[:6].lower() == "<html>" or result.find("</") > 0:
                req.content_type = "text/html"
            else:
                req.content_type = "text/plain"

        if req.method != "HEAD":
            req.write(result)
        else:
            req.write("")
        return apache.OK
    else:
        req.log_error("mod_python.publisher: %s returned nothing." % ` object `)
        return apache.HTTP_INTERNAL_SERVER_ERROR
Example #38
0
def handler(req):

    req.allow_methods(["GET", "POST"])
    if req.method not in ["GET", "POST"]:
        raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

    func_path = ""
    if req.path_info:
        func_path = req.path_info[1:] # skip first /
        func_path = func_path.replace("/", ".")
        if func_path[-1:] == ".":
            func_path = func_path[:-1] 

    # default to 'index' if no path_info was given
    if not func_path:
        func_path = "index"

    # if any part of the path begins with "_", abort
    if func_path[0] == '_' or func_path.count("._"):
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    # add req
    args = dict()
    args["req"] = req

    ## import the script
    path, module_name =  os.path.split(req.filename)
    if not module_name:
        module_name = "index"

    # get rid of the suffix
    #   explanation: Suffixes that will get stripped off
    #   are those that were specified as an argument to the
    #   AddHandler directive. Everything else will be considered
    #   a package.module rather than module.suffix
    exts = req.get_addhandler_exts()
    if req.extension:  # this exists if we're running in a | .ext handler
        exts += req.extension[1:] 
    if exts:
        suffixes = exts.strip().split()
        exp = "\\." + "$|\\.".join(suffixes)
        suff_matcher = re.compile(exp) # python caches these, so its fast
        module_name = suff_matcher.sub("", module_name)

    # import module (or reload if needed)
    # the [path] argument tells import_module not to allow modules whose
    # full path is not in [path] or below.
    module = apache.import_module(module_name, req.get_config(), [path])

    # does it have an __auth__?
    realm, user, passwd = process_auth(req, module)

    # resolve the object ('traverse')
    try:
        object = resolve_object(req, module, func_path, realm, user, passwd)
    except AttributeError:
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
    
    # not callable, a class or an aunbound method
    if not callable(object) or \
       str(type(object)) == "<type 'class'>" \
       or (hasattr(object, 'im_self') and not object.im_self):

        result = str(object)
        
    else:
        # callable, (but not a class or unbound method)

        # we need to weed out unexpected keyword arguments
        # and for that we need to get a list of them. There
        # are a few options for callable objects here:

        if str(type(object)) == "<type 'instance'>":
            # instances are callable when they have __call__()
            object = object.__call__

        if hasattr(object, "func_code"):
            # function
            fc = object.func_code
            expected = fc.co_varnames[0:fc.co_argcount]
        elif hasattr(object, 'im_func'):
            # method
            fc = object.im_func.func_code
            expected = fc.co_varnames[1:fc.co_argcount]

        # remove unexpected args unless co_flags & 0x08,
        # meaning function accepts **kw syntax
        if not (fc.co_flags & 0x08):
            for name in args.keys():
                if name not in expected:
                    del args[name]
                
        result = apply(object, (), args)

    if result:
        result = str(result)

        # unless content_type was manually set, we will attempt
        # to guess it
        if not req._content_type_set:
            # make an attempt to guess content-type
            if result[:100].strip()[:6].lower() == '<html>' \
               or result.find('</') > 0:
                req.content_type = 'text/html'
            else:
                req.content_type = 'text/plain'

        if req.method != "HEAD":
            req.write(result)
        else:
            req.write("")
        return apache.OK
    else:
        return apache.HTTP_INTERNAL_SERVER_ERROR
Example #39
0
from mod_python import apache
from mod_python import util
import hashlib
import datetime
import smtplib
import os
import string
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
from random import choice

cpss = apache.import_module("cpss")

max_image_size = 1024 * 1024 * 14  # 14 MiB
max_latex_size = 1024 * 1024 * 10  # This used to be uploaded pdf, now latex.
max_pdf_size = 1024 * 1024 * 14


class CpssUserErr(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class Connector:
    def __init__(self):
from mod_python import apache

import os
import sys
import vampire

# We can't use the "import" statement for "psp" because
# of strange problems in mod_python module loader.
# Namely, if "import" is used and PythonHandler is
# defined elsewhere as "mod_python.psp" and it gets
# loaded before this code, the "psp" module can not then
# be found. Instead use the mod_python module loader
# itself as then it always works.

#from mod_python import psp
psp = apache.import_module("mod_python.psp")

# Customised version of the PSP class which tailors
# execution of PSP pages to the Vampire execution
# environment. This will allow Vampire import hooks to
# work correctly where PSP code is in a file. The
# actual form fields are also made available directly.


class PSP(psp.PSP):
    def run(self, vars={}):

        code, req = self.code, self.req

        # Check whether the code is trying to make use of
        # session object. If it is, first look for session
def post_processing():
	from mod_python import apache
	import global_variables as g

	page_template = apache.import_module(g.g_page.get_page_template(), path=[g.g_main_path + '/scripts/page_templates/'])
	g.g_content.setContent(page_template.generate_page())
from mod_python import apache
markdown = apache.import_module('__init__')

import sys

## Import
def importETree():
    """Import the best implementation of ElementTree, return a module object."""
    etree_in_c = None
    try: # Is it Python 2.5+ with C implemenation of ElementTree installed?
        import xml.etree.cElementTree as etree_in_c
    except ImportError:
        try: # Is it Python 2.5+ with Python implementation of ElementTree?
            import xml.etree.ElementTree as etree
        except ImportError:
            try: # An earlier version of Python with cElementTree installed?
                import cElementTree as etree_in_c
            except ImportError:
                try: # An earlier version of Python with Python ElementTree?
                    import elementtree.ElementTree as etree
                except ImportError:
                    markdown.message(markdown.CRITICAL, "Failed to import ElementTree")
                    sys.exit(1)
    if etree_in_c and etree_in_c.VERSION < "1.0":
        markdown.message(markdown.CRITICAL, "For cElementTree version 1.0 or higher is required.")
        sys.exit(1)
    elif etree_in_c :
        return etree_in_c
    elif etree.VERSION < "1.1":
        markdown.message(markdown.CRITICAL, "For ElementTree version 1.1 or higher is required")
Example #43
0
'''Base classes and helpers for building zone specific tzinfo classes'''

from datetime import datetime, timedelta, tzinfo
from bisect import bisect_right
try:
    set
except NameError:
    from sets import Set as set

from mod_python import apache
pytz = apache.import_module('__init__')

__all__ = []

_timedelta_cache = {}


def memorized_timedelta(seconds):
    '''Create only one instance of each distinct timedelta'''
    try:
        return _timedelta_cache[seconds]
    except KeyError:
        delta = timedelta(seconds=seconds)
        _timedelta_cache[seconds] = delta
        return delta


_epoch = datetime.utcfromtimestamp(0)
_datetime_cache = {0: _epoch}

Example #44
0
def handler(req):

    # use direct access to _req for speed
    _req = req._req

    args = {}

    # process input, if any
    fs = util.FieldStorage(req, keep_blank_values=1)
    req.form = fs

    # step through fields
    for field in fs.list:

       # if it is a file, make File()
       if field.filename:
           val = File(field)
       else:
           val = field.value

       if args.has_key(field.name):
           args[field.name].append(val)
       else:
           args[field.name] = [val]

    # at the end, we replace lists with single values
    for arg in args.keys():
        if len(args[arg]) == 1:
            args[arg] = args[arg][0]

    # import the script
    path, module_name =  os.path.split(_req.filename)

    
    # get rid of the suffix
    module_name = suff_matcher.sub("", module_name)

    # import module (or reload if needed)
    module = apache.import_module(module_name, _req, [path])

    # does it have an __auth__?
    realm, user, passwd = process_auth(req, module)

    # resolve the object ('traverse')
    try:
        object = resolve_object(req, module, "handler", realm, user, passwd)
    except AttributeError:
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    # not callable, a class or an aunbound method
    if not callable(object) or \
       str(type(object)) == "<type 'class'>" \
       or (hasattr(object, 'im_self') and not object.im_self):

        result = str(object)
        
    else:
        # callable, (but not a class or unbound method)

        # we need to weed out unexpected keyword arguments
        # and for that we need to get a list of them. There
        # are a few options for callable objects here:

        if str(type(object)) == "<type 'instance'>":
            # instances are callable when they have __call__()
            object = object.__call__

        if hasattr(object, "func_code"):
            # function
            fc = object.func_code
            expected = fc.co_varnames[0:fc.co_argcount]
        elif hasattr(object, 'im_func'):
            # method
            fc = object.im_func.func_code
            expected = fc.co_varnames[1:fc.co_argcount]

    result = object(req, args)
    #result = str(args)

    if result:
        if type(result) is dict:
		location = result["Location"]
		del result["Location"]
		qs = urllib.urlencode(result)
		req.headers_out["Location"] = location + "?" + qs
		req.status = apache.HTTP_SEE_OTHER
		req.send_http_header()
		return apache.HTTP_SEE_OTHER

	result = str(result)

        # unless content_type was manually set, we will attempt
        # to guess it
        if not req._content_type_set:
            # make an attempt to guess content-type
            if string.lower(string.strip(result[:100])[:6]) == '<html>' \
               or string.find(result,'</') > 0:
                req.content_type = 'text/html'
            else:
                req.content_type = 'text/plain'

        req.send_http_header()
        req.write(result)
        return apache.OK
    else:
        return apache.HTTP_INTERNAL_SERVER_ERROR
Example #45
0
import os
import time
from mod_python import apache
directory = os.path.dirname(__file__) 
dist_crawl = apache.import_module('main_handler', path=[directory])
#import dist_crawl.main_handler
def do_more_stuff(req, links_str):
	links_with_depth = links_str.split("|||");
	links = []
	for each in links_with_depth:
		if each != "":
			each_link_and_depth = each.split("||")
			apache.log_error(str(each_link_and_depth))
			links.append(each_link_and_depth);
	apache.log_error(links_str);
	#apache.log_error(str(len(links_str)));
	#apache.log_error(str(links))
	result = dist_crawl.start_processing([], links, 0);
	map_res = result[0]
	result.pop(0);
	map_to_arr = []
	for each in map_res:
		map_to_arr.append([each] + map_res[each])
	result.insert(0, map_to_arr);
	more_results = result[0]
	ret_html = ""
	for res in more_results:
		ret_html = ret_html + "<tr>"
		for col in res:
			ret_html = ret_html + "<td>" + str(col) + "</td>"
Example #46
0
from mod_python import apache
from mod_python import Session
from mod_python import util
import os
import sys
import traceback
import smtplib
import pprint
import types
import hashlib
import datetime

_backend = apache.import_module("backend")
db = None
text = apache.import_module("text")

page = apache.import_module("page")

_connector = apache.import_module("connector")
connector = None

Template = apache.import_module("Template/__init__")

config_import = apache.import_module("config")
config = config_import.config

options = None # This will be filled with the SQL options.
session = None
req = None

def w(string):
Example #47
0
#!/usr/bin/env python

import os

WARPER_DIR = os.path.split(os.path.abspath(__file__))[0]

import tempfile
try:
    from mod_python import apache
    import tempfile
    warperModule = apache.import_module(os.path.join(WARPER_DIR,
                                                     "__init__.py"))
except ImportError, e:
    import cgi
    import cgitb
    cgitb.enable()

    import sys
    sys.path.append(WARPER_DIR)
    import warper as warperModule


def index(req, url=None, srs=None, hstosrs=None):
    """mod_python function"""
    if not srs:
        srs = hstosrs
    warper = warperModule.Warper(url, srs)
    image = warper.warp()
    tmpfile = tempfile.mktemp()
    image.save(tmpfile)
    req.content_type = warper.url.getArgument("format")
Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/).

Project website: <http://www.freewisdom.org/project/python-markdown/Fenced__Code__Blocks>
Contact: [email protected]

License: BSD (see ../docs/LICENSE for details) 

Dependencies:
* [Python 2.3+](http://python.org)
* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/)

"""

from mod_python import apache
markdown = apache.import_module('../__init__.py')

import re

# Global vars
FENCED_BLOCK_RE = re.compile( \
    r'(?P<fence>^~{3,})[ ]*(\{?\.(?P<lang>[a-zA-Z0-9_-]*)\}?)?[ ]*\n(?P<code>.*?)(?P=fence)[ ]*$',
    re.MULTILINE|re.DOTALL
    )
CODE_WRAP = '<pre><code%s>%s</code></pre>'
LANG_TAG = ' class="%s"'


class FencedCodeExtension(markdown.Extension):
    def extendMarkdown(self, md, md_globals):
        """ Add FencedBlockPreprocessor to the Markdown instance. """
Example #49
0
def handler(req):

    # using a closure is faster than an object-based implementation
    def start_response(status, headers, exc_info=None):

        if exc_info:
            try:
                raise exc_info[0], exc_info[1], exc_info[2]
            finally:
                exc_info = None

        # avoid str2int conversion for frequently used ones
        if status == '200':
            req.status = 200
        elif status == '301':
            req.status = 301
        elif status == '302':
            req.status = 302
        else:
            req.status = int(status[:3])

        # There is no need to req.set_content_length() or set
        # req.content_type because it will be in the headers anyhow.
        for k, v in headers:
            req.headers_out.add(k, v)

        return req.write

    options = req.get_options()

    ## Find the application callable

    app = None
    app_str = options['mod_python.wsgi.application']
    if app_str:
        if '::' in app_str:
            mod_str, callable_str = app_str.split('::', 1)
        else:
            mod_str, callable_str = app_str, 'application'
        config = req.get_config()
        autoreload, log = True, False
        if "PythonAutoReload" in config:
            autoreload = config["PythonAutoReload"] == "1"
        if "PythonDebug" in config:
            log = config["PythonDebug"] == "1"
        module = apache.import_module(mod_str, autoreload=autoreload, log=log)

        try:
            app = module.__dict__[callable_str]
        except KeyError:
            pass

    if not app:
        req.log_error(
            'WSGI handler: mod_python.wsgi.application (%s) not found, declining.'
            % ` app_str `, apache.APLOG_WARNING)
        return apache.DECLINED

    ## Build env

    env = req.build_wsgi_env()
    if env is None:
        # None means base_uri mismatch. The problem can be either
        # base_uri or Location, but because we couldn't be here if it
        # was Location, then it must be mod_python.wsgi.base_uri.
        base_uri = options.get('mod_python.wsgi.base_uri')
        req.log_error(
            "WSGI handler: req.uri (%s) does not start with mod_python.wsgi.base_uri (%s), declining."
            % ( ` req.uri `, ` base_uri `), apache.APLOG_WARNING)
        return apache.DECLINED

    ## Run the app

    response = None
    try:
        response = app(env, start_response)
        [req.write(token) for token in response]
    finally:
        # call close() if there is one
        if type(response) not in (list, tuple):
            getattr(response, 'close', lambda: None)()

    return apache.OK
Example #50
0
import MySQLdb

from mod_python import apache
cpss = apache.import_module("../cpss.py")

try:
    from string import Template
except ImportError:
    from stringtemplate import Template

PITemplate = Template("""    <PI>
      <name>${name}</name>
      <email>${email}</email>
      <affiliation>${affil}</affiliation>
      <US>${us}</US>
    </PI>
""")

CoITemplate = Template("""    <CoI>
      <name>${name}</name>
      <email>${email}</email>
      <affiliation>${affil}</affiliation>
      <US>${us}</US>
    </CoI>
""")

# Check recieverBand
# Why is isFlex filled with a variable called fill?
ObsblockTemplate = Template("""  <obsblock>
    <obsblockID>${obsblock}</obsblockID>
    <observationType>${observation_type}</observationType>
Example #51
0
#!/usr/bin/python2.4
#
# Written 2007

# mod_python handler for vim commands

from mod_python import apache

vcg_path = '/home/demew/public_html/sandbox/python/'
vim_command_grabber = apache.import_module('vim_command_grabber',
                                           path=[vcg_path])

class GadgetModPy(object):
  
  def __init__(self):
    """ Instantiates a GadgetModPy object. """
    self.__gg = vim_command_grabber.GadgetGrabber()

  def GrabCommand(self):
    """ Grabs the command from the gadget grabber.

      Returns: tuple of two strings: (command, description).
    """
    return self.__gg.GrabTodaysCommand()

def index(req):
  gmp = GadgetModPy()
  s = """ \
        <html>
        <body>
        Today's Vim Command!<br />
Example #52
0
#!/usr/bin/env python
'''
$Id: tzfile.py,v 1.8 2004/06/03 00:15:24 zenzen Exp $
'''

from cStringIO import StringIO
from datetime import datetime, timedelta
from struct import unpack, calcsize

from mod_python import apache

tzinfo = apache.import_module('tzinfo')

from tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo
from tzinfo import memorized_datetime, memorized_timedelta


def build_tzinfo(zone, fp):
    head_fmt = '>4s 16x 6l'
    head_size = calcsize(head_fmt)
    (magic, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt,
     charcnt) = unpack(head_fmt, fp.read(head_size))

    # Make sure it is a tzinfo(5) file
    assert magic == 'TZif'

    # Read out the transition times, localtime indices and ttinfo structures.
    data_fmt = '>%(timecnt)dl %(timecnt)dB %(ttinfo)s %(charcnt)ds' % dict(
        timecnt=timecnt, ttinfo='lBB' * typecnt, charcnt=charcnt)
    data_size = calcsize(data_fmt)
    data = unpack(data_fmt, fp.read(data_size))
Example #53
0
#!/usr/bin/python
# -*- coding= utf-8

from mod_python import Session
from mod_python import apache
fonctions = apache.import_module("fonctions")


def index(req):
    req.content_type = "text/html"
    conn = fonctions.connexionBD()
    cursor = conn.cursor()
    id_util = req.form["id_util"]
    login = req.form["login"]
    requete = "select id_util, mdp from util where login = %s"
    cursor.execute(requete, (login))
    tup = cursor.fetchone()
    if tup is None:
        msg = "Login inexistant"
        lien = fonctions.lien("form-connexion.py",
                              "Retour au formulaire de connexion")
    else:
        (id_util, mdp) = tup
        if mdp != req.form["mdp"]:
            msg = "Mot de passe incorrect"
            lien = fonctions.lien("form-connexion.py",
                                  "Retour au formulaire de connexion")
        else:
            session = Session.Session(req)
            session["id_util"] = id_util
            session["login"] = login
Example #54
0
#!/usr/bin/env python
from mod_python import apache, Session
import os, shutil
import zipfile
my_globals = apache.import_module("gnome_panel_extensions_org_globals")

def html_foot():
    return '''
</body>
</html>
'''


def upload(req, bundle, uploadtype, category):
    
    import shelve
    base_dir = os.path.split(os.path.split(req.filename)[0])[0]
    os.chdir(base_dir)

    return_page = '''<?xml version="1.0"?>

<!DOCTYPE html 
	PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
 <title>Upload</title>
 <link rel="stylesheet" type="text/css" href="../../styles/global.css"/>
Example #55
0
import os
import time
from mod_python import apache
directory = os.path.dirname(__file__)
dist_crawl = apache.import_module('main_handler', path=[directory])


#import dist_crawl.main_handler
def do_more_stuff(req, links_str):
    links_with_depth = links_str.split("|||")
    links = []
    for each in links_with_depth:
        if each != "":
            each_link_and_depth = each.split("||")
            apache.log_error(str(each_link_and_depth))
            links.append(each_link_and_depth)
    apache.log_error(links_str)
    #apache.log_error(str(len(links_str)));
    #apache.log_error(str(links))
    result = dist_crawl.start_processing([], links, 0)
    map_res = result[0]
    result.pop(0)
    map_to_arr = []
    for each in map_res:
        map_to_arr.append([each] + map_res[each])
    result.insert(0, map_to_arr)
    more_results = result[0]
    ret_html = ""
    for res in more_results:
        ret_html = ret_html + "<tr>"
        for col in res: