Пример #1
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

from libs.bottle import Bottle, route, static_file
from libs.bottle import debug, run
from libs.bottle import jinja2_view as view

app = Bottle()

@app.route("/")
@view("templates/hello.html")
def index():
    return { 'title': 'Simple TODO List' }

@app.route("/static/<filename:path>")
def static(filename):
    return static_file(filename, root='static/')

if __name__ == '__main__':
    debug(True)
    run(app, reloader=True, host='0.0.0.0', port=8081)
from libs.bottle import route, template, run


@route("/hello/<name>")
def index(name):
    return template("<b>Hello {{name}}</b>!", name=name)


run(host="localhost", port=8080)
Пример #3
0
    return json.dumps({
        "taskset": hobbit_hood.taskset,
        "tags": hobbit_hood.categories,
        "matrix": hobbit_hood.matrix.tolist()
    })











if __name__ == "__main__":




    # Create student directory
    try:
        os.mkdir("Students")
    except:
        pass

    run(host='0.0.0.0', port=27000)

Пример #4
0
 def run_server():
     run(host=args.host,
         port=args.port,
         debug=args.debug,
         reloader=args.debug,
         quiet=not args.debug)
Пример #5
0

@route('/')
def index():
    return 'Welcome to Analytics API !'


@route('/projections/<projection_type>', method='POST')
def make_projection(projection_type):
    # get post data
    received_data = request.json

    data = received_data['data']
    window = received_data['window']

    # get predictor
    predictor = PredictorFactory.get_predictor(projection_type)

    try:
        # exec predictor
        result = predictor.predict(data, window)

        # format result
        response.content_type = 'application/json'
        return json.dumps(result)
    except ValueError as e:
        response.status = 500
        return e

run(host='localhost', port=8085)
Пример #6
0
                                                "%Y-%m-%d")
    ultimo_dia_de_mes_fecha = primer_dia_de_mes_fecha + relativedelta(months=1)
    primer_dia_de_mes = calendar.timegm(primer_dia_de_mes_fecha.utctimetuple())
    ultimo_dia_de_mes = calendar.timegm(ultimo_dia_de_mes_fecha.utctimetuple())

    query = """SELECT * FROM facturas WHERE fecha > "%s" AND fecha < "%s" ORDER by %s ASC""" % \
      (primer_dia_de_mes, ultimo_dia_de_mes, orden)
    datos = c.execute(query)

    return template("templates/xmes_listado.html", {"datos": datos})


@route("/listado/xmes")
def xmeses():
    conn = sqlite3.connect(config.getVar("dir_vault") + "facturas.db")
    c = conn.cursor()
    query = """SELECT fecha FROM facturas ORDER by fecha ASC LIMIT 1 """
    datos = c.execute(query)
    import time
    fecha = time.gmtime(int(datos.fetchone()[0]))
    conn.close()
    return template("templates/xmes.html", {
        "datos": fecha,
        "hoy": datetime.now()
    })


#Ejecutamos servidor
if __name__ == "__main__":
    run(host='localhost', port=8001)
Пример #7
0
from libs.bottle import route, run,request,template

@route('/hello')
def hello():
    return "Hello World XXX!"

@route('/queryvars')
def display_forum():
    id = request.query.id
    page = request.query.page or '1'
    return template('Forum ID: {{id}} (page {{page}})', id=id, page=page)


run(host='0.0.0.0', port=8080, debug=True)
Пример #8
0
    return data.json()



@route('/api/students')
def create_students():
    return json.dumps(StudentEngine.get_students())

@route('/api/create_students')
def create_students():
    Student_Create.generate()


    return json.dumps({
        'message': "OK",
        'students': StudentEngine.get_students()
    })










if __name__ == "__main__":
    run(host='0.0.0.0', port=8080)

Пример #9
0
from libs.bottle import route, template, run

@route('/recherche/<name>')
def index(name):
    return "Hello {{name}}"

run(host='0.0.0.0', port=8081)
Пример #10
0
    print(data)
    return data.json()


@route('/api/student/<student>/taskset')
def taskset(student):

    data = req.get(
        "http://*****:*****@route('/api/students')
def create_students():
    return json.dumps(StudentEngine.get_students())


@route('/api/create_students')
def create_students():
    Student_Create.generate()

    return json.dumps({
        'message': "OK",
        'students': StudentEngine.get_students()
    })


if __name__ == "__main__":
    run(host='0.0.0.0', port=8080)
Пример #11
0
    elif text == "1":
        # Business logic for first level response
        response = "CON Choose account information you want to view \n"
        response += "1. Account number \n"
        response += "2. Account balance"

    elif text == "2":
        # Business logic for first level response
        phoneNumber = "+254711XXXYYY"
        # This is a terminal request. Note how we start the response with END
        response = "END Your phone number is {}".format(phoneNumber)

    elif text == "1*1":
        # This is a second level response where the user selected 1 in the first instance
        accountNumber = "ACC1001"
        # This is a terminal request. Note how we start the response with END
        response = "END Your account number is {}".format(accountNumber)

    elif text == "1*2":
        # This is a second level response where the user selected 1 in the first instance
        balance = "KES 1,000"
        # This is a terminal request. Note how we start the response with END
        response = "END Your balance is {}".format(balance)

    # Return the response as an HTTP request
    return response


# Run the default bottle app
run(host='0.0.0.0', port='8080', debut=True, reloader=True)
Пример #12
0
def main():
	run(host=DEFAULT_HOST,port=DEFAULT_PORT, debug=True)
Пример #13
0
def index():#on affiche la page principale avec le formulaire
	ville="''"
	activite="''"
	maps = []
	table = []
	conn = sqlite3.connect('static/sports_pdl.db')# in order to have access to the database you must connect
	cursor = conn.cursor()
	cursor.execute("""SELECT DISTINCT code_postal, commune FROM installation WHERE code_postal != '' AND commune != '' ORDER BY code_postal ASC""")
	#request that return the postal code and the name of the city
	tab = []

	for x in cursor.fetchall(): #separator for each row of the cursor
		tab.append(x[0]+" - "+x[1])
	
	cursor2 = conn.cursor()
	cursor2.execute("""SELECT DISTINCT act_code, lib_act FROM activite ORDER BY act_code ASC""")
	#request that return the postal code and the name of the city
	act = []

	for y in cursor2.fetchall(): #separator for each row of the cursor
		act.append(str(y[0])+" - "+y[1])

	return template('index', tab=json.dumps(tab), act=json.dumps(act),num_act=0,code_postal=0,table=json.dumps(table),maps=json.dumps(maps),ville=ville,activite=activite)

@route('/static/:path#.+#', name='static')#on définit une route pour aller chercher les autres fichiers utiles et images
def static(path):
    return static_file(path, root='static')


run(host='localhost', port=8080)
Пример #14
0
from libs.bottle import route, request, run, static_file
import json
from dao.Dao import *


#route pour permettre à la page html de charger le js
@route('/js')
def js_route():
    return static_file('script.js', root='./public/js')


#route qui donne les installation d'une ville
@route('/api/insta/<filepath:path>')
def insta_ville(filepath):
    nom, num = get_Installation(filepath)
    jsonObj = []
    for i in range(len(nom)):
        chaineJson = {"num": str(num[i]), "name": nom[i]}
        jsonObj.append(chaineJson)
    return {"installations": jsonObj}


#route home / accueil
@route('/')
def home():
    return static_file('index.html', root='./public', mimetype="text/html")


run(host='localhost', port=10078)
Пример #15
0
def intert(uri):
    text = bottle.request.POST.get('text', '')
    data = {'uri': uri, 'text':text}
    try:
        docfinder.add_document(uri, text)
    except docfinder.DuplicateURI:
        data['status'] = 'error'
        data['error'] = 'DuplicateURI'
    else:
        data['status'] = 'OK'
    bottle.response.content_type = 'application/json'
    return json.dumps(data, indent=2)

# This adds the capability to send commands
@bottle.get('/cmd/v1/<command>')
def execute(command):
    argv = command.split()
    try:
        output = subprocess.check_output(argv)
    except Exception as e:
        data = {'status': 'error',
                'error': str(e)}
    else:
        data = {'status': 'OK',
                'output': output}
    return json.dumps(data, indent=2)


if __name__ == '__main__':
    bottle.run(host='localhost', port=8080)
Пример #16
0
    elif text == "1":
        # Business logic for first level response
        response = "CON Choose account information you want to view \n"
        response += "1. Account number \n"
        response += "2. Account balance"

    elif text == "2":
        # Business logic for first level response
        phoneNumber = "+254711XXXYYY"
        # This is a terminal request. Note how we start the response with END
        response = "END Your phone number is {}".format(phoneNumber)

    elif text == "1*1":
        # This is a second level response where the user selected 1 in the first instance
        accountNumber  = "ACC1001"
        # This is a terminal request. Note how we start the response with END
        response = "END Your account number is {}".format(accountNumber)

    elif text == "1*2":
        # This is a second level response where the user selected 1 in the first instance
        balance  = "KES 1,000"
        # This is a terminal request. Note how we start the response with END
        response = "END Your balance is {}".format(balance)

    # Return the response as an HTTP request
    return response

# Run the default bottle app
run(host='0.0.0.0',port='8080',debut=True,reloader=True)
from libs.bottle import route, static_file, run
import json

from services.activities.ActivityService import allActivities


@route('/api/activities')
def activities():
    activities = allActivities()
    jsonActivities = []
    for activity in activities:
        jsonActivities.append(activity.__dict__)
    return {"activities": jsonActivities}


@route('/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='./public')


run(host='localhost', port=8888)
Пример #18
0
def run_handler():
    run(App, host='0.0.0.0', port=8080)
Пример #19
0
            web.redirect(obj) #headers are (perhaps) set by its own server
        else:
            log("ASK SID."+sid+"-> will return to a file-like (%s) of size (%s)"%(contentType,str(size)))
            if contentType: web.response.content_type = contentType
            if size: web.response.content_length = str(size)
            return obj
    else:
        log("ASK SID."+sid+"-> unknown sid ?!")
        web.abort(404)

@web.get('/')
@web.view("web")
def index():
    return {"msg":"PyPlaydar Server is running ..."}

@web.error(404)
def Error404(code):
    return '404 Not found'

@web.error(400)
def Error400(code):
    return '400 Bad Request'

@web.error(500)
def Error500(code):
    return '500 Server Error'

if __name__=="__main__":

    web.run(host="0.0.0.0",port=60210,server="cherrypy")
Пример #20
0
def select(uri):
    #See posting to API text file for an example post
    data = {'uri': uri}
    try:
        content = docfinder.get_document(uri)
    except docfinder.UnknownURI as e:
        data['status'] = 'error'
        data['error'] = repr(e)
    else:
        data['status'] = 'OK'
        data['content'] = content
    # below tries to automatically download the text without displaying
    # bottle.response.content_type = 'application/text'
    bottle.response.content_type = 'application/json'
    return json.dumps(data, indent=2)


# host.com/resource?querygoeshere
# localhost:9000/docfinder/v1/document?q=barry,zip
@bottle.route('/docfinder/v1/document')
def search():
    keywords = bottle.request.query.get('q', '').split(',')
    results = docfinder.search(*keywords)
    data = {'status': 'OK', 'documents': results}
    bottle.response.content_type = 'application/json'
    return json.dumps(data, indent=2)


if __name__ == '__main__':
    bottle.run(host='localhost', port=9000)
Пример #21
0
from libs import bottle
from libs.bottle import run
from src.dispatcher import *
from config import Config
from init_db import init_tables

init_tables()
Config().refresh_config()

#run(host='localhost', port=8090, debug=True)

if __name__ == '__main__':
    try:
        from paste import gzipper  # @UnresolvedImport
        app = gzipper.middleware(bottle.app())
        from cherrypy import wsgiserver  # @UnusedImport @UnresolvedImport

        print "Paste Gzip activated, CherryPy activated"
        run(app=app, host='localhost', port=Config().ServerPort, server='cherrypy')
    except:
        try:
            from cherrypy import wsgiserver  # @UnusedImport @Reimport @UnresolvedImport
            print "Paste Gzip not found, CherryPy activated"
            run(host='localhost', port=Config().ServerPort, server='cherrypy')
        except:
            print "Paste Gzip not found, CherryPy not found Debug mode"
            run(host='localhost', port=Config().ServerPort, debug=True)
Пример #22
0
                "SELECT a.activity, i.name, e.nomEq, a.city from installations i, equipements e, activities a where a.city=e.city and e.numInstal=i.num and a.city=\""
                + city + "\";")
        #Si l'utilisateur a sélectionné une city et une activité, on affiche toutes les activités correspondant à celle sélectionnée dans la city.
        if (city != "all" and activity != "all"):
            req = c.execute(
                "SELECT a.activity, i.name, e.nomEq, a.city from installations i, equipements e, activities a where a.city=e.city and e.numInstal=i.num and a.city=\""
                + city + "\" and a.activity=\"" + activity + "\";")
        #Si l'utilisateur a sélectionné seulement une activité on affiche toutes les citys où l'on peut pratiquer cette activité
        if (city == "all" and activity != "all"):
            req = c.execute(
                "SELECT \"" + activity +
                "\", i.name, e.nomEq, a.city from installations i, equipements e, activities a where a.city=e.city and e.numInstal=i.num and a.activity=\""
                + activity + "\" limit 20;")
        if (city == "all" and activity == "all"):
            req = []
        if req != []:
            list = [a for a in req]
            c.close()
            #on envoie ces données au template tmpt_correct.
            return template('tpl/tmpt_results', results=list)
        else:
            return ("Veuillez rentrer au moins une ville ou une activité")

    except Exception as error:
        print("Unexpected error: {0}".format(error))
        return ("erreur")


#on lance le serveur sur localhost, sur le port choisi
run(host='localhost', port=8182)
Пример #23
0
	conn = sqlite3.connect(config.getVar("dir_vault") + "facturas.db")
	c = conn.cursor()
	import calendar
	from dateutil.relativedelta import relativedelta

	primer_dia_de_mes_fecha = datetime.strptime("%s-%s-%s" % (ano, mes,1), "%Y-%m-%d")
	ultimo_dia_de_mes_fecha = primer_dia_de_mes_fecha + relativedelta(months=1)
	primer_dia_de_mes = calendar.timegm(primer_dia_de_mes_fecha.utctimetuple())
	ultimo_dia_de_mes = calendar.timegm(ultimo_dia_de_mes_fecha.utctimetuple())
	
	query = """SELECT * FROM facturas WHERE fecha > "%s" AND fecha < "%s" ORDER by %s ASC""" % \
			(primer_dia_de_mes, ultimo_dia_de_mes, orden)
	datos = c.execute(query)
	
	return template("templates/xmes_listado.html", {"datos":datos} )
	
@route("/listado/xmes")
def xmeses():
	conn = sqlite3.connect(config.getVar("dir_vault") + "facturas.db")
	c = conn.cursor()
	query = """SELECT fecha FROM facturas ORDER by fecha ASC LIMIT 1 """
	datos = c.execute(query)
	import time
	fecha = time.gmtime(int(datos.fetchone()[0]))
	conn.close()
	return template("templates/xmes.html", {"datos":fecha, "hoy":datetime.now()} )

#Ejecutamos servidor
if __name__ == "__main__":
	run(host='localhost', port=8001)