Exemple #1
0
    def get_custom_renderer(self, dir_path, layout=True, use_jinja= False):
        """
        Create a template renderer on templates in the directory specified, and returns it.
        :param dir_path: the path to the template dir. If it is not absolute, it will be taken from the root of the inginious package.
        :param layout: can either be True (use the base layout of the running app), False (use no layout at all), or the path to the layout to use.
                       If this path is relative, it is taken from the INGInious package root.
        """

        # if dir_path/base is a absolute path, os.path.join(something, an_absolute_path) returns an_absolute_path.
        root_path = inginious.get_root_path()

        if isinstance(layout, str):
            layout_path = os.path.join(root_path, layout)
        elif layout is True:
            layout_path = os.path.join(root_path, self._layout)
        else:
            layout_path = None

        if use_jinja:
            return render_jinja(os.path.join(root_path, dir_path),
                             globals=self._template_globals)
        else:
            return web.template.render(os.path.join(root_path, dir_path),
                                   globals=self._template_globals,
                                   base=layout_path)
Exemple #2
0
def getAdminRender():
    render = render_jinja(
        'tpl/admin',
        encoding = 'utf-8'
    )

    return render
Exemple #3
0
def getRender():
    """ get render for public pages """
    render = render_jinja(
        'templates',                      # set template directory
        encoding = 'utf-8',               # encoding
    )
    return render
Exemple #4
0
 def GET(self, page=None):
     try:
         page = int(page) if page else 1
     except ValueError:
         page = 1
     offset = (page - 1) * PER_PAGE
     db = web.database(dbn='sqlite', db=DB)
     quote_count = db.query(
         "select count(*) as count from quote where channel='{}'".format(
             CHANNEL))[0].count
     quotes = db.select('quote',
                        where="channel = '{}'".format(CHANNEL),
                        order='date desc',
                        limit='$l',
                        offset='$o',
                        vars={
                            'l': PER_PAGE,
                            'o': offset
                        })
     quotes = [fixDates(quote) for quote in quotes]
     pages = int(math.ceil(quote_count / PER_PAGE))
     render = render_jinja(TEMPLATES)
     return render.list(quotes=quotes,
                        channel=CHANNEL,
                        analytics=GOOGLE_ANALYTICS,
                        page=page,
                        pages=pages)
Exemple #5
0
def getRender():
    render = render_jinja(
        'tpl',
        encoding = 'utf-8'
    )

    return render
Exemple #6
0
def load_render(views, **globals):
    '''Add the renderer to the shared context.'''
    render = render_jinja(views, encoding='utf-8',
                          extensions=['jinja2.ext.do'])
    render._lookup.globals.update(globals)
    def inner():
        web.ctx.render = render;
    return inner
Exemple #7
0
def render(tmp_dir):
    gconf = config.data
    gconf['uptime'] = serverInfo()
    render = render_jinja([config.pp + 'templates/', config.pp + 'templates/' + tmp_dir], encoding='utf-8')
    render._lookup.globals.update(session=web.config._session, gconf=gconf)
    render._lookup.filters.update(filter.filters)

    return render
 def inner():
     render = render_jinja(views,
                           encoding='utf-8',
                           extensions=['jinja2.ext.do', AssetsExtension])
     render._lookup.assets_environment = env
     render._lookup.globals.update(
         dict(DEV=config.DEV, VERSION=get_version()))
     web.ctx.render = render
Exemple #9
0
def rendeHtml(template, **args):
    web.header('Content-Type', 'text/html')

    globals['v'] = time.time()
    globals['cookies'] = web.cookies()

    render = render_jinja(path + '/templates', encoding='utf-8', globals=globals)
    print path + '/templates'
    return getattr(render, template)(**args)
Exemple #10
0
def getAdminRender():
    render = render_jinja(
            os.getcwd() + '/templates/admin',
            encoding = 'utf-8',
        )
    myFilters = {'avatar':templatefilters.avatar,'notnull':templatefilters.notnull,
        'formnote':templatefilters.formnote, 'content':templatefilters.content}
    render._lookup.filters.update(myFilters)
    return render
Exemple #11
0
def render(tmp_dir):
    gconf = config.gconf
    gconf['debug'] = web.config.debug
    gconf['uptime'] = serverInfo()
    render = render_jinja(['templates/', 'templates/' + tmp_dir], encoding='utf-8')
    render._lookup.globals.update(session=web.config._session, gconf=gconf)
    render._lookup.filters.update(myfilter.filters)

    return render
Exemple #12
0
 def GET(self, templatename):
     root_path = os.environ['ROOT_PATH']
     template_path = os.path.join(root_path, 'templates')        
     try:
         templatename = 'tests/%s' % templatename
         render = template.render_jinja(template_path)
         return getattr(render, templatename, '')()
     except:
         logging.exception("got an error in loading %s" %templatename)
         return 'template %s not found' % templatename
Exemple #13
0
def load_render_with_assets(views, env, **globals):
    '''Add the renderer to the shared context.'''
    from webassets.ext.jinja2 import AssetsExtension
    render = render_jinja(views, encoding='utf-8',
                          extensions=['jinja2.ext.do', AssetsExtension])
    render._lookup.assets_environment = env
    render._lookup.globals.update(globals)
    def inner():
        web.ctx.render = render;
    return inner
Exemple #14
0
def render(template, context, locale=None):
    if locale:
        set_locale(locale)
    jinja = render_jinja(
        TEMPLATE_PATH,
        globals={'gettext' : ugettext_for_locale(LOCALE)},
        extensions=['jinja2.ext.i18n'],
        encoding='utf-8',
        )
    jinja._lookup.filters.update(TEMPLATE_FILTERS)
    template = jinja._lookup.get_template(template)
    return template.render(**context)
Exemple #15
0
def getAdminRender():
    render = render_jinja(
        os.getcwd() + '/templates/admin',
        encoding='utf-8',
    )
    myFilters = {
        'avatar': templatefilters.avatar,
        'notnull': templatefilters.notnull,
        'formnote': templatefilters.formnote,
        'content': templatefilters.content
    }
    render._lookup.filters.update(myFilters)
    return render
Exemple #16
0
def index():
    import web
    from web.contrib.template import render_jinja
    from models import profile, database

    db = database.database()
    urls = (
                '/', 'hello'
                        )
    
    render = render_jinja(
                  'templates',                 # Set template directory.
                   encoding = 'utf-8',         # Encoding.
                           )
def load_render(views):
    """Add the renderer to the shared context.

    Inputs:
        views path containing application views
    """
    render = render_jinja(
            views, encoding='utf-8',
            extensions=['jinja2.ext.do', AssetsExtension])
    render._lookup.assets_environment = env
    render._lookup.globals.update(dict(DEV=config.DEV,
                                        VERSION=get_version()))
    def inner():
        web.ctx.render = render;
    return inner
Exemple #18
0
 def GET(self, page=None):
     try:
         page = int(page) if page else 1
     except ValueError:
         page = 1
     offset = (page - 1) * PER_PAGE
     db = web.database(dbn='sqlite', db=DB)
     quote_count = db.query("select count(*) as count from quote where channel='{}'".format(CHANNEL))[0].count
     quotes = db.select('quote', where="channel = '{}'".format(CHANNEL),
                        order='date desc', limit='$l', offset='$o',
                        vars={'l': PER_PAGE, 'o': offset})
     quotes = [fixDates(quote) for quote in quotes]
     pages = int(math.ceil(quote_count / PER_PAGE))
     render = render_jinja(TEMPLATES)
     return render.list(quotes=quotes, channel=CHANNEL,
                        analytics=GOOGLE_ANALYTICS, page=page, pages=pages)
Exemple #19
0
def render(module_path, parent=''):
    """
    自定义渲染渲染
    :param module_path: 当前的文件名
    :param parent: 当前文件的父文件名
    :return:
    """
    cfg = config.cfg
    cfg['debug'] = 1 if web.config.debug else 0
    cfg['vt'] = config.vesion if config.run_mode in ["deploy"] else int(
        time.time())

    tempath = os.path.split(module_path)[1].replace('.pyc',
                                                    '').replace('.py', '')
    render = render_jinja(['view/', 'view/' + parent + "/" + tempath],
                          encoding='utf-8')
    render._lookup.globals.update(session=web.config._session, cfg=cfg)
    render._lookup.filters.update(filter.filters)

    return render
Exemple #20
0
from web.contrib.template import render_jinja

import config

URLS = (
    '/yumbo/diagram/(.*)\.(.+)', 'Diagram',
    '/yumbo/', 'Root'
)
FORMATS = {
        'gif':      'image/gif',
        'jpeg':     'image/jpeg',
        'jpg':      'image/jpeg',
        'png':      'image/png',
        'svg':      'image/svg+xml'
}
JINJA = render_jinja(config.app_root + '/' + config.template_root, encoding = 'utf-8')

def draw(text, fmt):
    echo = subprocess.Popen(['echo', text], stdout=subprocess.PIPE)
    yumbodot = subprocess.Popen(config.yumbodot_path,
                                stdin=echo.stdout, stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE)
    dot = subprocess.Popen([config.dot_path, '-T', fmt],
                           stdin=yumbodot.stdout, stderr=subprocess.PIPE,
                           stdout=subprocess.PIPE)
    (out, derr) = dot.communicate()
    (_, yderr) = yumbodot.communicate()
    if yumbodot.returncode != 0:
        raise Exception(yderr)
    elif dot.returncode != 0:
        raise Exception(derr)
Exemple #21
0
import web
from web import form
from web.contrib.template import render_jinja

# Database connection
db = web.database(dbn='postgres', user='******', pw='etwin', db='webpy_test')

view = render_jinja('views', encoding='utf-8')


class Staff:
    def GET(self, id=None):
        staffs = db.select('staff')
        if id is None:
            context = {'staffs': staffs}
            return view.staff_list(context)
        else:
            vars = dict(id=id)
            results = db.select('staff', where="id=$id", vars=vars, _test=True)
            if results is not None:
                staff_result = db.query(results)
                for staff in staff_result:
                    return view.staff_detail({'staff': staff})
            raise web.seeother('/error')

    def POST(self, staff_id=None):
        if staff_id is None:
            i = web.input()
            # x = web.input(myfile={})
            names = i.names
            role = i.role
Exemple #22
0
import web
import json
import core

from models import *
from web.contrib.template import render_jinja

view = render_jinja('view/visitor')

class create:
    def GET(self):
        return view.signup(user = User.status())

    def POST(self):
        """
        @return: json(@error)
        """
        try:
            User.create(dict(web.input()))
            return json.dumps({'error': 0})
        except AttributeError:
            # Missing information
            return json.dumps({'error': 1})
        except Exception as exception:
            errorCode =  int(exception.message)
            if errorCode > 1:
                return json.dumps({'error': errorCode})
            else:
                # Unknown error
                return json.dumps({'error': 9999})
Exemple #23
0
parser.add_argument(
    "exp_config",
    metavar="EXP_config",
    type=Path,
    nargs=1,
    help="configuration file to run experiments",
)
args = parser.parse_args()

experiments = []
exp_location = ""
order = "random"
output_file = Path("./results.txt")
results_dir = ""
template_dir = "templates"
render = render_jinja(template_dir, encoding="utf-8")

with open(args.exp_config[0]) as fp:
    experiments = [Path(x.strip()) for x in fp.readlines()]

for experiment in experiments:
    try:
        os.symlink(experiment, Path("./static/", experiment.stem))
    except FileExistsError:
        os.unlink(Path("./static/", experiment.stem))
        os.symlink(experiment, Path("./static/", experiment.stem))


def serve_experiment(experiment):
    exp_name = experiment.stem
    context = generate_experiment_context(exp_name, "/static")
Exemple #24
0
    "/",
    "Index",
    "/index",
    "Index",
    "/register",
    "Register",
    "/success",
    "Success",
)

app = web.application(urls, globals())
session = web.session.Session(app,
                              web.session.DiskStore('sessions'),
                              initializer={'count': 0})
render = render_jinja(
    'template',  # template default path
    encoding='utf-8',  # encoding
)


class Index:
    form = web.form.Form(
        web.form.Textbox('login_name',
                         web.form.notnull,
                         size=30,
                         description="Username"),
        web.form.Password('password',
                          web.form.notnull,
                          size=30,
                          description="Password"),
        web.form.Button('Login'),
    )
Exemple #25
0
urls = (
    '/', 'index',
    '/login', 'login',
    '/msg', 'msg',
    '/gender', 'gender',
    '/main', 'main',
    '/femain', 'femain',
   '/getMalePic', 'getMalePic',
   '/getFePic', 'getFePic',
    '/last', 'last',
    '/finalPic', 'finalPic'
)

#render = web.template.render('resource')
render = render_jinja(
        'resource',
        encoding = 'utf-8',
    )

app = web.application(urls, globals())
#web.config.debug = False
#session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'uid':0})
#session
if web.config.get('_session') is None:
    session = web.session.Session(app, web.session.DiskStore('sessions'),\
     {'uid': 0, 'color':'#444444', 'imgUrl':0})
    web.config._session = session
else:
    session = web.config._session

bksjw='http://bksjw.hust.edu.cn/'
hub='http://hub.hust.edu.cn/'
Exemple #26
0
Fichier : user.py Projet : e42s/uss
import os
import json
import sqlite3
import time
import hashlib
import re

urls = (
        '/tree', 'Tree',
        '/page', 'Page',
        '/changepasswd', 'Changepasswd', #简化方案
        '/.*', 'Page'
        )

app = web.application(urls, locals())
render = render_jinja('webapps/user/templates/', encoding='utf-8',)

#########################################################
print 'user.py db_dir:', db_dir
print 'user.py sql_dir:', sql_dir
user_db = LocalSqliteDB('user', db_dir, sql_dir)
db = os.path.join(db_dir, 'user.db')
#########################################################

def notfound():
    return web.notfound(render.notfound())
app.notfound = notfound

def login_required(func):
    def new_func(*args, **argvkw):
        session = web.ctx.session
Exemple #27
0
import web
import os
import numpy as np
import scipy.io as sio
from sklearn.svm import SVC

from web.contrib.template import render_jinja
from process_email import process_email, email_features
from spam_train import spam_train

template_dir = os.path.join(os.path.dirname(__file__), '.')
render = render_jinja(
    template_dir,
    encoding='utf-8',
)

model = None # store model so won't have to compute over and over

class index:
    def GET(self):
        return render.front(email="", error="")

    def POST(self):
        global model
        email = web.input().email

        if not email:
            error = "we need some email contents"
            return render.front(email=email, error=error)
        else:
            features = np.reshape(email_features(process_email(email)), (1, -1))
Exemple #28
0
        s['count'] = 1
        count = s['count']
    s['count'] = count + 1
    s.close()
    return count
    
t_globals = {
            "ctx" : web.ctx,
            "team_infor" : db.select("team_infor")[0],
            "grade_dict" : grade_dict,
            "grade_manage_dict" : grade_manage_dict,
            "gravatar_dir" : r"/static/gravatar/",
            "visitor_count" : get_visitor,
        }

render = render_jinja(os.path.join(ABSPATH,"templates/"),encoding="utf-8",globals = t_globals)
render_admin = render_jinja(os.path.join(ABSPATH,"templates/admin/"),encoding="utf-8",globals = t_globals)



app = web.application(urls,globals())
application = app.wsgifunc()

store = web.session.DBStore(db, 'sessions')
sess = web.session.Session(app, store)

class Upload(object):
    
    def __init__(self,upfile):
        import os
        self.file = upfile
Exemple #29
0
#coding=utf8

import web
from web.contrib.template import render_jinja
from models import Get_Menu,Get_Shows

render = render_jinja(
    'templates',
    encoding = 'utf8',
)


class Redirect:
    def GET(self,path):
        web.seeother('/'+path)
        
class Index:
    def GET(self):
        m = Get_Menu()
        s = Get_Shows()
        return render.index(m=m,s=s)
    
class Category:
    def GET(self,id):
        return 'category %s' % int(id,10)

class Detail:
    def GET(self,id):
        return 'detail-%d' % int(id,10)
Exemple #30
0
    global APP
    return APP


# store = web.session.DBStore(db, 'sessions')
# session = web.session.Session(get_app(), store, initializer={'loggedin': False})
# SESSION = web.session.Session(get_app(), store, initializer={'loggedin': False})


def get_session():
    global SESSION
    return SESSION


# Jinja2 Template options
render = render_jinja(absolute('app/views'), encoding='utf-8')

render._lookup.globals.update(ses=get_session(), ourDistricts=ourDistricts)


def put_session(session):
    global SESSION
    SESSION = session
    render._lookup.globals.update(ses=session)


def csrf_token():
    session = get_session()
    if 'csrf_token' not in session:
        from uuid import uuid4
        session.csrf_token = uuid4().hex
Exemple #31
0
from web.contrib.template import render_jinja

# 下面的import 是从common目录里面导入的。
sys.path.append( os.path.join(os.getcwd(), "common") )
import config


#web.config.debug=False


urls=(
    '/user','User',
        )

app = web.application(urls,globals())
render = render_jinja('templates', encoding = "utf8")
if web.config.get('_session') is None:
    session = web.session.Session(\
            app,web.session.DiskStore('sessions'),\
            initializer={'logged':0}
            )
    web.config._session=session
else:
    session = web.config._session

#让子应用可以使用session。
def session_hook():
    web.ctx.session = session
app.add_processor(web.loadhook(session_hook))

Exemple #32
0
    })
    web.config._session = session
else:
    session = web.config._session

web.config.session_parameters['cookie_name'] = 'gotit_session_id'
web.config.session_parameters['cookie_domain'] = "gotit.asia"
web.config.session_parameters['timeout'] = 600,  #in seconds
web.config.session_parameters['ignore_expiry'] = True
web.config.session_parameters['ignore_change_ip'] = True
web.config.session_parameters['secret_key'] = 'wqerjkhbasdfhsdakyarweqr'
web.config.session_parameters['expired_message'] = '您需要重新登录!'
# end sessions

render = render_jinja('templates',
                      encoding='utf-8',
                      globals={'context': session})


class index:
    '''
    new  索引页面
    '''

    # @memorize(index_cache)
    def GET(self):
        return render.index()


class login:
    '''
Exemple #33
0
#-*- coding: UTF-8 -*-
import web
import sys
from web.contrib.template import render_jinja
import codecs

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

urls = ('/', 'Upload')

render = render_jinja("template", encoding="utf-8")


class Upload:
    def GET(self):
        web.header("Content-Type", "text/html; charset=utf-8")
        return getattr(render, 'index')()

    def POST(self):
        input = web.input()
        x = input.myfile
        y = input.algorithm
        print y
        filedir = 'D:/working/bysj/data'  # change this to the directory you want to store the file in.
        if 'myfile' in x:  # to check if the file-object is created
            filepath = x.myfile.filename.replace(
                '\\',
                '/')  # replaces the windows-style slashes with linux ones.
            filename = filepath.split(
                '/'
Exemple #34
0
from ua.common.ua_conf import db_dir

import json
import datetime
import ConfigParser
import sqlite3
import os


urls = (
        '/rsrc', 'Rsrc',

        '/page', 'Page',
        )

render = render_jinja('webapps/syst/templates/alert', encoding='utf-8',)
app = web.application(urls, locals())


def notfound():
    return web.notfound(render.notfound())
app.notfound = notfound

db = os.path.join(db_dir, "alert.db")

def login_required(func):
    def new_func(*args, **argvkw):
        session = web.ctx.session
        if session.user == 'anonymous' or session.user == '':
#            return render.notlogin()
             raise web.seeother('/login?tip=%s' % u'请登录!')
Exemple #35
0
    'Index',
    '/view/(\d+)',
    'View',
    '/new',
    'New',
    'New',
    '/delete/(\d+)',
    'Delete',
    '/edit/(\d+)',
    'Edit',
)

t_globals = {'datestr': web.datestr}

render = render_jinja(
    'templates',  # 模板路径
    encoding='utf-8',  #编码
)


class Index:
    def GET(self):
        """
        show index page
        """
        posts = model.get_posts()
        for post in posts:
            print post['title']
            print post['content']
        return render.index(posts=posts)

Exemple #36
0
# _*_ coding:utf-8 _*_
from web.contrib.template import render_jinja
import web
import urllib2,urllib
import re,json
urls=(
    '/','Index',#get post
    # '/(js|css|images)/(.*)', 'static',
    '/s','So',
    '/key','Key',
)

render = render_jinja(
    'templates'
    # 'static'
)#实例化模板文件

def getdata(wd):#获取百度数据
    #类似于 爬虫
    wd=urllib.quote(wd.encode('utf-8'))
    # url='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=%s' %(wd)
    url='https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%s' %(wd)
    add_headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'
    }
    req=urllib2.Request(url,headers=add_headers)
    html=urllib2.urlopen(req).read()
    return html


def getkey(wd):
Exemple #37
0
    "social.backends.tripit.TripItOAuth",
    "social.backends.clef.ClefOAuth2",
    "social.backends.twilio.TwilioAuth",
    "social.backends.xing.XingOAuth",
    "social.backends.yandex.YandexOAuth2",
    "social.backends.podio.PodioOAuth2",
    "social.backends.mineid.MineIDOAuth2",
    "social.backends.wunderlist.WunderlistOAuth2",
)
web.config[setting_name("LOGIN_REDIRECT_URL")] = "/done/"


urls = ("^/$", "main", "^/done/$", "done", "", social_app.app_social)


render = render_jinja("templates/")


class main(object):
    def GET(self):
        return render.home()


class done(social_app.BaseViewClass):
    def GET(self):
        user = self.get_current_user()
        return render.done(user=user, backends=backends(user))


engine = create_engine("sqlite:///test.db", echo=True)
Exemple #38
0
 def init_plugin(self):
     self.render = render_jinja(self._module.__path__,
                                encoding=self.encoding)
Exemple #39
0
import web
from web.contrib.template import render_jinja
import json

import ip_find

urls = ("/ip", "IPFind",
        "/api/ip/(.*)", "IPFindAPI")

app = web.application(urls, globals())
render = render_jinja("templates", encoding='utf-8')
ipInfo = ip_find.IPInfo("data/qqwry.dat")

def find_loc_by_ip(ip):
    try:
        i = ipInfo
        (c, a) = i.getIPAddr(ip);
        c = unicode(c, 'utf-8')
        a = unicode(a, 'utf-8')
    except:
        raise
    return (c, a)

class IPFind:
    def GET(self):
        return render.ip()

class IPFindAPI:
    def GET(self, ip):
        try:
            c, a = find_loc_by_ip(ip)
Exemple #40
0
# -*- coding: utf-8 -*-
import web
import time
from model import db
from web.contrib.template import render_jinja

render = render_jinja("templates/admin", encoding="utf-8")


class fees_admin:
    def GET(self):
        return render.fees_admin()

    def POST(self):
        return "post"
Exemple #41
0
urls = (
    '/syst_deploy',
    'Syst_deploy',
    '/syst_test',
    'Syst_test',
    '/syst_start',
    'Syst_start',
    '/syst_stop',
    'Syst_stop',
    '/page',
    'Page',
)

render = render_jinja(
    'webapps/syst/templates/ctrl',
    encoding='utf-8',
)
app = web.application(urls, locals())


def notfound():
    return web.notfound(render.notfound())


app.notfound = notfound


def login_required(func):
    def new_func(*args, **argvkw):
        session = web.ctx.session
        if session.user == 'anonymous' or session.user == '':
Exemple #42
0
Fichier : srvc.py Projet : e42s/uss
from ua.common.ua_conf import *

import web
from web.contrib.template import render_jinja

import os

urls = (
        '/tab_mds', 'Tab_mds',
        '/tab_cds', 'Tab_cds',
        '/tab_c60', 'Tab_c60',

        '/page', 'Page',
        )

render = render_jinja('webapps/node/templates/srvc', encoding='utf-8',)
app = web.application(urls, locals())

#########################################################
oops_db_dir = os.path.join(os.path.dirname(current_dir()), db_dir)
oops_sql_dir = os.path.join(os.path.dirname(current_dir()), sql_dir)

node_db = LocalSqliteDB('node', oops_db_dir, oops_sql_dir)
#########################################################


def notfound():
    return web.notfound(render.notfound())
app.notfound = notfound

def login_required(func):
Exemple #43
0
 def render(self, page_dir='static/pages/', encode='utf-8'):
     rend = render_jinja(page_dir, encoding=encode)
     return rend
Exemple #44
0
    'social.backends.tripit.TripItOAuth',
    'social.backends.twilio.TwilioAuth',
    'social.backends.xing.XingOAuth',
    'social.backends.yandex.YandexOAuth2',
)
web.config[setting_name('LOGIN_REDIRECT_URL')] = '/done/'


urls = (
    '^/$', 'main',
    '^/done/$', 'done',
    '', social_app.app_social
)


render = render_jinja('templates/')


class main(object):
    def GET(self):
        return render.home()


class done(social_app.BaseViewClass):
    @strategy()
    def GET(self):
        user = self.get_current_user()
        return render.done(user=user, backends=backends(user))


engine = create_engine('sqlite:///test.db', echo=True)
Exemple #45
0
web.config.debug = True

urls = (
    '/',
    'List',
    '/list',
    'List',
    '/add',
    'Add',
    '/delete/(\d+)',
    'Delete',
    '/update/(\d+)',
    'Update',
)

render = render_jinja('templates/gift', encoding='utf-8')

render._lookup.globals.update(web=web)

db = web.database(dbn='sqlite', db='gift.db')

app = web.application(urls, globals())

gift_form = form.Form(form.Textbox('name', form.notnull),
                      form.Textarea('detail', form.notnull),
                      form.Button('submit', type='submit'))


class List:
    def GET(self):
        gifts = db.select('gift', what='id,name')
Exemple #46
0
    'login',
    '/logout',
    'logout',
    '/configuration/(.+)',
    'configuration',
    '/monitor/(.+)',
    'monitor',
    '/description/(.+)',
    'description',
    '/results/(.+)',
    'results',
)

#render = web.template.render('templates/')
render = render_jinja(
    'templates/',
    encoding='utf-8',
)
web.config.debug = False
app = web.application(urls, globals())
session = web.session.Session(app,
                              web.session.DiskStore('sessions'),
                              initializer={'count': 0})
web.cache = {}
web.cache["tuner_thread"] = None
web.cache["cetune_status"] = "idle"


class index:
    def GET(self):
        if session.get('logged_in', False):
            return render.index(username=session.username)
Exemple #47
0
Fichier : moni.py Projet : e42s/uss
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on 20101205
Author: zkz
"""
from ua.common.bridge import moni as bridge_moni

import web
from web.contrib.template import render_jinja

urls = ("/page", "Page")

render = render_jinja("webapps/syst/templates/moni", encoding="utf-8")
app = web.application(urls, locals())


def notfound():
    return web.notfound(render.notfound())


app.notfound = notfound


def login_required(func):
    def new_func(*args, **argvkw):
        session = web.ctx.session
        if session.user == "anonymous" or session.user == "":
            #            return render.notlogin()
            raise web.seeother("/login?tip=%s" % u"请登录!")
        else:
Exemple #48
0
    '/rack_list',
    'Rack_list',
    '/node_role_set',
    'Node_role_set',
    '/node_role_list',
    'Node_role_list',
    '/node_dtls',
    'Node_dtls',
    '/node_add',
    'Node_add',
    '/node_rrd',
    'Node_rrd',
)

render = render_jinja(
    'webapps/div/templates',
    encoding='utf-8',
)
app = web.application(urls, locals())


def notfound():
    return web.notfound(render.notfound())


app.notfound = notfound


def login_required(func):
    def new_func(*args, **argvkw):
        session = web.ctx.session
        if session.user == 'anonymous' or session.user == '':
Exemple #49
0
#coding=utf-8

import web  
from web.contrib.template import render_jinja

urls = (  
    '/hello', 'hello',
    '/ctx', 'ctx'
)  

render = render_jinja('', encoding='utf-8',)

# 添加请求前的钩子函数
def my_loadhook():
    print('my load hook')

# 添加请求后的钩子函数
def my_unloadhook():
    print('my unload hook')

class hello:  
    def GET(self):  
        return render.jinja_index(name=u'张三', 
                date=u'2019-12-06 15:21', 
                addr=u'中国')

class ctx:
    def GET(self):
        return str(web.ctx)

app = web.application(urls, globals())  
Exemple #50
0
def loadSqla(handler):
    try:
        sql_session.commit()
        return handler()
    except web.HTTPError:
        raise
    except Exception:
        sql_session.rollback()
    finally:
        sql_session.commit()


# jinja2模板加载
app_root = os.path.dirname(__file__)
templates_path = os.path.join(app_root, 'templates').replace('\\', '/')
render = render_jinja(templates_path, encoding='utf-8')

# webpy session
web.config.session_parameters = web.utils.storage({
    'cookie_name': 'session_id',
    'cookie_domain': None,
    'cookie_path': None,
    'timeout': 86400,  # 24 * 60 * 60, # 24 hours in seconds
    'ignore_expiry': True,
    'ignore_change_ip': True,
    'secret_key': 'fLjUfxqXtfNoIldA0A0J',
    'expired_message': 'Session expired',
    'httponly': True,
    'secure': False
})  # webpy cookbook和api文档里面都没有提到,可以看webpy的源码来进行设置
Exemple #51
0
import os, sys, json
import web, jinja2
from web.contrib.template import render_jinja

import main as main_module

render = render_jinja(
    'templates',  # 设置模板路径.
    encoding='utf-8',  # 编码.
)


def add(x, y):
    return x + y


render._lookup.filters['add'] = add


class HttpBase:
    def __init__(self):
        print("request start")

    def __del__(self):
        print("request end")


class Index(HttpBase):
    def GET(self):
        return render.index()
Exemple #52
0
Author: zkz
"""
import web
from web.contrib.template import render_jinja

import json

urls = (
    '/rsrc',
    'Rsrc',
    '/page',
    'Page',
)

render = render_jinja(
    'webapps/fsys/templates/auth',
    encoding='utf-8',
)
app = web.application(urls, locals())


def notfound():
    return web.notfound(render.notfound())


app.notfound = notfound


def login_required(func):
    def new_func(*args, **argvkw):
        session = web.ctx.session
        if session.user == 'anonymous' or session.user == '':
Exemple #53
0
#!/usr/bin/env python

import os
import re
import sys
from time import strftime, strptime, time, localtime, mktime
import urllib
import web
from web.contrib.template import render_jinja

curdir = os.path.dirname(__file__)
if curdir not in sys.path: sys.path.append(curdir)

import xtide

render = render_jinja(curdir + '/templates')

def green_red_yellow(tide_site, current_site, state):
    if tide_site and current_site:
        if state == 0 or state == 2: return "red"
        if state == 1: return "green"
        return "yellow"
    if tide_site:
        return "green" if state else "red"
    if current_site:
        return "red" if state else "green"

def box(tide_site = None, current_site = None, tag = None,
        target = None, name = None, url = None, this_time = None):
    this_time = this_time if this_time else time()
    start_time = mktime(strptime(strftime("%Y-%m-%d 14:00", localtime(this_time)), "%Y-%m-%d %H:%M"))
Exemple #54
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import _env
import os
import web
from os.path import join
from redis import StrictRedis
from web.contrib.template import render_jinja
from lib.redis_key import RedisKey


render = render_jinja(
    'template',
    encoding='utf-8',
)
img_type = (
        'jpg',
        'bmp',
        'png',
        'gif',
)
PWD = _env.PWD

redis = StrictRedis(host='localhost', port=6379, db=0)
redis_key = RedisKey(redis)

HOST = 'img.lerry.tk'
IMG_ROOT = '/home/lerry/imgs'
CACHE_DIR = join(PWD, 'static/.cache')
DB_NAME = join(PWD, 'img.db')
TABLE_NAME = 'img_list'
import sae
import sae.const
import web

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

from web.contrib.template import render_jinja

# jinja2模板
app_root = os.path.dirname(__file__)
templates_path = os.path.join(app_root, 'templates\global').replace('\\', '/')

global_render = render_jinja(
    templates_path,  # 设置模板路径.
    encoding='utf-8',  # 编码.
)

admin_render = render_jinja(
    os.path.join(app_root, 'templates\manage').replace('\\', '/'),  # 设置模板路径.
    encoding='utf-8',  # 编码.
)

# sqlalchemy
# create_engine(数据库://用户名:密码(没有密码则为空)@主机名:端口/数据库名',echo =True)
MYSQL_DB = sae.const.MYSQL_DB
MYSQL_USER = sae.const.MYSQL_USER
MYSQL_PASS = sae.const.MYSQL_PASS
MYSQL_HOST_M = sae.const.MYSQL_HOST
MYSQL_HOST_S = sae.const.MYSQL_HOST_S
MYSQL_PORT = int(sae.const.MYSQL_PORT)
Exemple #56
0
Fichier : flog.py Projet : e42s/uss
    loginfo, loginfo, loginfo, loginfo, loginfo
    """
urls = (
        '/tab_ctrl_mng', 'Tab_ctrl_mng', #used 单个服务
        '/field_ctrl', 'Field_ctrl', #used 单个服务
        '/tab_rrd', 'Tab_rrd', #used 整个集群

        '/srvc/(.*)', 'Srvc', # used 单个服务

        '/page/(.*)', 'Page',
        '/logOption', 'LogOption', #used
        '/loginfo', 'LogInfo', #used
        '/srvc_dtls', 'Srvc_dtls',
        )

render = render_jinja('webapps/fsys/templates/flog', encoding='utf-8',)
app = web.application(urls, locals())

#########################################################
oops_db_dir = os.path.join(os.path.dirname(current_dir()), db_dir)
oops_sql_dir = os.path.join(os.path.dirname(current_dir()), sql_dir)

node_db = LocalSqliteDB('node', oops_db_dir, oops_sql_dir)
#########################################################


def notfound():
    return web.notfound(render.notfound())
app.notfound = notfound

def login_required(func):
Exemple #57
0
    # after handling a request we are autocommiting all changes
    context.orm = scoped_session(sessionmaker(bind=engine))
    try:
        return handler()
    except HTTPError:
       context.orm.commit()
       raise
    except:
        context.orm.rollback()
        raise
    finally:
        context.orm.commit()

app = application(urls, globals())
wsgi = app.wsgifunc()
render = render_jinja('static', encoding = 'utf-8')

class Home:
    def GET(self):
        return render.index_sea()

class Register:
    def POST(self):
        i = web.input()
        firstname = i.get('firstname')
        lastname = i.get('lastname')
        nickname = i.get('nickname')
        email = i.get('email')
        new_user = User(firstname, lastname, nickname, email)
        if i.has_key('avatar'):
            new_user.avatar = i.avatar
Exemple #58
0
    'social.backends.stocktwits.StocktwitsOAuth2',
    'social.backends.tripit.TripItOAuth',
    'social.backends.clef.ClefOAuth2',
    'social.backends.twilio.TwilioAuth',
    'social.backends.xing.XingOAuth',
    'social.backends.yandex.YandexOAuth2',
    'social.backends.podio.PodioOAuth2',
    'social.backends.mineid.MineIDOAuth2',
    'social.backends.wunderlist.WunderlistOAuth2',
    'social.backends.upwork.UpworkOAuth',
)
web.config[setting_name('LOGIN_REDIRECT_URL')] = '/done/'

urls = ('^/$', 'main', '^/done/$', 'done', '', social_app.app_social)

render = render_jinja('templates/')


class main(object):
    def GET(self):
        return render.home()


class done(social_app.BaseViewClass):
    def GET(self):
        user = self.get_current_user()
        return render.done(user=user, backends=backends(user))


engine = create_engine('sqlite:///test.db', echo=True)
#     output_predict = clf.predict(input_data[n_train:]).tolist()
#     output_total = output_data[:n_train] + output_predict
#     return output_total
#   
# def Kernel_Regression(input_data, output_data, ratio):
#     n_train = int(np.shape(input_data)[0]*ratio)
#     output_predict = []
#     clf = svm.SVR()
#     for i in range(np.shape(input_data)[0] - n_train):
#         clf.fit(input_data[:][:n_train + i], output_data[:n_train + i])    
#         output_predict.append(clf.predict(input_data[n_train + i]).tolist()[0])
#     output_total = output_data[:n_train] + output_predict
#     return output_total

# ### Templates
render = render_jinja('./templates', encoding = 'utf-8')

class Stock:
    name = ""
    interval = ""
    ratio = ""
    start = ""
    end = ""
     
    def __init__(self, symbol):
        self.symbol = symbol
    def analyze(self, interval,ratio,start,end):
        self.interval = intervaldict[str(interval)]
        self.ratio = ratiodict[ratio]
        self.start = start
        self.end = end