Esempio n. 1
0
    def _app(self, **kwargs):
        app = kwargs.pop('app', bottle.Bottle(catchall=False))

        kwargs.setdefault('dbuser', self.USER)
        kwargs.setdefault('dbpass', self.PASS)
        kwargs.setdefault('dbname', self.DBNAME)
        kwargs.setdefault('dbhost', self.DBHOST)
        plugin = bottle_mysql.Plugin(**kwargs)

        app.install(plugin)

        return app
Esempio n. 2
0
#!/usr/bin/env python
# −*− coding:utf−8 −*−
import bottle
from bottle import route, run, install, template, get, post, request, static_file
import _mysql
import bottle_mysql
import re
from stemming import Stemming

plugin = bottle_mysql.Plugin(dbuser='******',
                             dbpass='******',
                             dbname='suma1',
                             dbhost='127.0.0.1')
install(plugin)


@route("/", method='GET')
def startseite():
    # _mysql.connect(host="127.0.0.1",user="******",port=3306,passwd="1234",db="suma2")
    return template('templates/index.tpl')


@route("/search_fast", method='GET')
def searc_fast(db):
    searchtext = request.params.get('searchtext')
    if searchtext == None:
        return template('src/index.tpl')
    #searchtext = request.forms.get('searchtext')

    if not request.params.get('Suchart') == None:
        if request.params.get('Suchart') == 'regular':
Esempio n. 3
0
import bottle
import bottle_mysql

app = bottle.Bottle()
plugin = bottle_mysql.Plugin(dbuser='******',
                             dbpass='******',
                             dbname='info708')
app.install(plugin)
Esempio n. 4
0
import bottle
import bottle_mysql

app = bottle.Bottle()
# dbhost is optional, default is localhost
plugin = bottle_mysql.Plugin(dbhost='172.18.1.13',
                             dbuser='******',
                             dbpass='******',
                             dbname='test')
app.install(plugin)


@app.route('/show/<name>/<pass1>')
def show(name, pass1, db):
    db.execute('SELECT * from users where name=%s and pass=password(%s)', (
        name,
        pass1,
    ))
    row = db.fetchone()
    if row:
        return row
    return "error"


app.run(host='', port=8080)
Esempio n. 5
0
from random import choice
from string import ascii_letters, digits

from beaker.middleware import SessionMiddleware
import bottle_mysql
from bottle import run, template, request, redirect, static_file, Bottle, abort
from check import exist, is_auth, validate_email

session_opts = {
    'session.type': 'ext:database',
    'session.cookie_expires': True,
    'session.url': 'mysql://*****:*****@localhost:3306/todo',
    'session.timeout': 300,
}
bottle_app = Bottle()
plugin = bottle_mysql.Plugin(dbuser='******', dbpass="******", dbname='todo')
bottle_app.install(plugin)

app = SessionMiddleware(bottle_app, session_opts)


@bottle_app.hook('before_request')
def csrf_protect():
    if request.method == 'POST':
        sess = request.environ.get('beaker.session')
        req_token = request.forms.get('csrf_token')
        # if no token is in session or it doesn't match the request one, abort
        if 'csrf_token' not in sess or sess['csrf_token'] != req_token:
            abort(403)

Esempio n. 6
0
import bottle
import bottle_mysql
import models
import dbm
import time
from beaker.middleware import SessionMiddleware

logging.basicConfig(filename='smartycity-DBM.log', level=logging.DEBUG)

app = bottle.Bottle()
app.config.load_config('app.conf')
# dbhost: optional, default is localhost
# keyword: The keyword argument name that triggers the plugin (default: ‘db’).
plugin = bottle_mysql.Plugin(dbuser=app.config['mysql.user'],
                             dbpass=app.config['mysql.pwd'],
                             dbname=app.config['mysql.dbname'],
                             dbhost=app.config['mysql.host'],
                             dictrows=['mysql.dictrows'] == 'True')
app.install(plugin)


def getCurrentDayTime():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


logging.info(getCurrentDayTime() + ' bottle_mysql installed.')

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 300,  # 300s
    'session.data_dir': './data',
Esempio n. 7
0
import os
import bottle
import bottle_mongo
from bottle import route, run, template
import bottle_mysql
from bottle import Bottle, redirect
from bottle.ext.mongo import MongoPlugin
from bson.json_util import dumps

index_html = "My first web app! By <strong>{{ author}}</strong>."
app = bottle.Bottle()
plugin = bottle_mysql.Plugin(dbuser='******', dbpass='******')
app.install(plugin)


@route('/')
def index():
    return template(index_html, author='Erik')


@route('/name/<name>')
def name(name):
    return template(index_html, author=name)


# @route('/show/:<tem>')
# def show(item, db):
# 	db.execute('SELECT * from items where name="%s"',(item,))
# 	row = db.fetchone()
# 	if row:
# 		return template('showitem',page=row)
Esempio n. 8
0
from bottle import Bottle, run, post, error
from bottle import template
import bottle_mysql

plugin = bottle_mysql.Plugin(dbuser='******', dbpass='******', dbname='angelo')

app = Bottle()
app.install(plugin)


@app.route('/')
@app.route('/hello/<name>')
def greet(name='Stranger'):
    return template('Hello {{name}}, how are you?', name=name)


@post('/login')  # or @route('/login', method='POST')
def do_login():
    username = request.forms.get('username')
    password = request.forms.get('password')
    if check_login(username, password):
        return "<p>Your login information was correct.</p>"
    else:
        return "<p>Login failed.</p>"


@app.route('/show/:<item>')
def show(item):
    dbname.execute(
        'SELECT * from angelo.temperatura')  # where sensorid="%s"', (item,))
    row = dbname.fetchone()
Esempio n. 9
0
        abort(400, 'No data received')

    entity = json.loads(data)
    if not entity.has_key('shirtId'):
        abort(400, 'No shirtId specified')

    existed = mongo['shirts'].find_one({'shirtId': entity.get('shirtId')})
    if not existed:
        abort(404, 'This shirt is not existed')

    mongo['shirts'].remove({'shirtId': entity.get('shirtId')})


#Mysql database
plugin = bottle_mysql.Plugin(dbuser='******',
                             dbpass='******',
                             dbname='assignment3')
install(plugin)


@route('/shoe/:shoeId')
def singleShoe(shoeId, db):
    db.execute('SELECT * from shoes where shoe_id="%s"', (int(shoeId), ))
    row = db.fetchone()
    if not row:
        abort(404, 'No shoe is found')

    return row


@route('/shoes', method='PUT')
Esempio n. 10
0
#!/usr/bin/python

import bottle
import bottle_mysql

app = bottle.Bottle()
plugin = bottle_mysql.Plugin(dbuser='******', dbpass='******', dbname='test')
app.install(plugin)


@app.route('/show/<item>')
def show(item, db):
    db.execute('select * from sutdent where gender="%s"', (item, ))
    row = db.fetchone()
    if row:
        return template('showitem', page=row)
    return HTTPError(404, "Page not found")


run(host='192.168.10.11', port=8000, debug=True)
Esempio n. 11
0
# IP Address Validation Regex (used globally)
ippattern = re.compile(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$')


def validation(auth, auth_value):
    """Validate the JWT Authentication"""
    if 'username' in auth and auth[auth_value] == API_USER:
        return True

    return False


# Initialise the Bottle App, and add the MySQL and JWT plugins
app = bottle.Bottle()
plugin = bottle_mysql.Plugin(dbuser=DB_USER, dbpass=DB_PASS, dbname=DB_NAME, dbhost=DB_HOST)
app.install(plugin)
app.install(JwtPlugin(validation, API_PASS, algorithm='HS256'))


_allow_origin = '*'
_allow_methods = 'PUT, GET, POST, DELETE, OPTIONS'
_allow_headers = 'Authorization, Origin, Accept, Content-Type, X-Requested-With'


@app.hook('after_request')
def enable_cors():
    """Add headers to enable CORS"""

    response.headers['Access-Control-Allow-Origin'] = _allow_origin
    response.headers['Access-Control-Allow-Methods'] = _allow_methods
Esempio n. 12
0
def server_static(filepath):
    return static_file(filepath, root=STATIC_HTML_DIR)


#JOBs API
@route('/jobs', method=['GET', 'POST'])
def fetch_jobs(db):
    status = request.query.status or 'all'
    query = request.query.q or ''
    return impl.query_jobs(db, status, query)


#Shortlisted API
@route('/jobs/<jobid>/shortlisted', method=['GET'])
def fetch_shortlisted(db, jobid):
    return impl.query_shortlisted(db, jobid)


#Interviews API
@route('/jobs/<jobid>/interviews/<candid>', method=['GET'])
def fetch_interviews(db, jobid, candid):
    return impl.query_interviews(db, jobid, candid)


application = default_app()
plugin = bottle_mysql.Plugin(dbhost='xxxxxxxxx',
                             dbuser='******',
                             dbpass='******',
                             dbname='xxxx')
application.install(plugin)
Esempio n. 13
0
import bottle
import bottle_mysql

app = bottle.Bottle()
plugin = bottle_mysql.Plugin(dbhost='localhost',
                             dbuser='******',
                             dbpass='******',
                             dbname='mysql')
app.install(plugin)


@app.route('/')
def show(db):
    db.execute('SELECT Host, User from user;')
    row = db.fetchone()
    if row:
        return "host=%s and user=%s" % (row["Host"], row["User"])
    bottle.response.status = 404
    return None


app.run(host='localhost', port=8080, debug=True, reloader=True)
Esempio n. 14
0
from bottle import Bottle, request
import bottle_mysql
import csv
import os
import sys
import config

application = Bottle()
plugin = bottle_mysql.Plugin(dbuser=config.user, dbpass=config.password, dbname='gpu')
application.install(plugin)

def ensure_number(s):
  if s == "[Not Supported]":
    return None
  try:
    float(s)
    return s
  except ValueError:
    return None

@application.post('/')
def post(db):
    print(request.body)
    ip = request.environ.get('REMOTE_ADDR')
    reader = csv.DictReader(request.body, skipinitialspace=True)
    for row in reader:
      print(row)
      result = db.execute("""INSERT INTO gpu SET
        `ip` = %s,
        `timestamp` = %s,
        `name` = %s,
Esempio n. 15
0
### bottlepage gurugeek 11 September 2019

import bottle
import bottle_mysql
from urllib.error import HTTPError
from bottle import route, run, template, static_file, redirect

app = bottle.Bottle()
# dbhost is optional, default is localhost
plugin = bottle_mysql.Plugin(dbuser='******',
                             dbpass='******',
                             dbhost='sql.fyi',
                             dbname='washnotes')
app.install(plugin)


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


@app.route('/')
def index():
    return redirect('/index')


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

Esempio n. 16
0
from bottle import *
from googleapiclient.discovery import build
from oauth2client import client

import backend
from update_google_fit import get_and_store_fit_data

bad_activities = "(0,3,5,109,110,111,112,117,118)"

# bottle web framework init
app = Bottle()
application = app
# dbhost is optional, default is localhost
plugin = bottle_mysql.Plugin(
    dbhost=backend.config.get('database_config', 'dbhost'),
    dbport=int(backend.config.get('database_config', 'dbport')),
    dbuser=backend.config.get('database_config', 'dbuser'),
    dbpass=backend.config.get('database_config', 'dbpass'),
    dbname=backend.config.get('database_config', 'dbname'))
app.install(plugin)


def require_key():
    key = request.query.get('key', '')
    if key != backend.API_key:
        abort(httplib.UNAUTHORIZED, "invalid API key")


@app.get('/health')
def health_check(db):
    if db:
        return "database connection alive: " + str(db.connection)
Esempio n. 17
0
import bottle_mysql
import json
from bottle import route, request, run, get, view, template, error, install
from bottle import static_file
import datetime
from time import mktime


class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%H:%M:%S")
        return json.JSONEncoder.default(self, obj)


install(bottle_mysql.Plugin(dbuser='******', dbpass='******', dbname='temps'))


@error(404)
def error404(error):
    return 'Nothing here, sorry'


@route('/')
@route('/mote')
def mote_list(db):
    output = template('motes_list', motes=getMotes(db), db=db)
    return output


@route('/chart/<mote>/<sensor>')
Esempio n. 18
0
from bottle import route, run, template, request, redirect, Bottle
import bottle_mysql

app = Bottle()
plugin = bottle_mysql.Plugin(dbuser='******', dbpass='******', dbname='blog')
app.install(plugin)

__login = ""
__password = ""
__signed_in = False


@app.route('/')
def hello(login="", password=''):
    print("index", __login, __password)
    return template('templates/index', login=__login, password=__password)


@app.route('/info')
def info():
    return template('templates/info',
                    login=__login,
                    password=__password,
                    signed_in=__signed_in)


@app.route('/login')
def login():
    return template('templates/login')

Esempio n. 19
0
import bottle
from bottle import route, run, template

import bottle_mysql
plugin = bottle_mysql.Plugin(dbuser='******', dbpass='******', dbname='db')

#import pymysql
#import sys

con = pymysql.connect('todo.dat')

print "Creating database/table..."

with con:
    cur = con.cursor()
    # DROP TABLE
    #cur.execute("DROP TABLE IF EXISTS test")

    # CREATE TABLES
    cur.execute(
        "CREATE TABLE todo (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, desc TEXT, datetime TEXT )"
    )

con.close()
print "Database/table created."