Example #1
0
def main():
    graph = getGraph()
    graph.query = graph.queryd
    index = ImageIndex(graph)
    iset = ImageSet(graph, index)

    @route('/update', methods=['POST'])
    def update(request):
        log.info('updating %r', request.args)
        index.update(URIRef(request.args['uri'][0]))
        log.info('done updating')
        # schedule updateSorts? maybe they need to schedule themselves
        return 'indexed'
    
    @route('/set.json')
    def main(request):
        pairs = []
        for k, vs in request.args.items():
            for v in vs:
                pairs.append((k, v))
        q = queryFromParams(pairs)
        result = iset.request(q)
        return json.dumps(result)

    run("0.0.0.0", networking.imageSet()[1])
Example #2
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("-H", "--host", help="Host/IP to bind HTTP to", default="localhost")
    parser.add_argument("-p", "--port", help="TCP port to bind HTTP to", default=8000)
    #parser.add_argument("-v", "--verbose", help="increase output verbosity", action='count', default=0)

    args = parser.parse_args()

    run(args.host, args.port)
Example #3
0
def listen():
    @route('/', methods=['POST'])
    def do_post(request):
        content = json.loads(request.content.read())
        response = "ok"
        routing(content)
        return response

    @route('/healthz')
    def check(request):
        return "Ok"

    run("0.0.0.0", 8090)
Example #4
0
def main():
    graph = getGraph()
    graph.query = graph.queryd
    index = ImageIndex(graph)
    iset = ImageSet(graph, index)

    @route('/update', methods=['POST'])
    def update(request):
        log.info('updating %r', request.args)
        index.update(URIRef(request.args['uri'][0]))
        log.info('done updating')
        # schedule updateSorts? maybe they need to schedule themselves
        return 'indexed'

    @route('/created', methods=['GET'])
    def created(request):
        def tOut(uri):
            t = index.byUri[uri]['t']
            if t is None:
                return 'None'
            return t.isoformat()

        return '\n'.join(tOut(URIRef(uri)) for uri in request.args['uri'])

    @route('/set.json')
    def main(request):
        pairs = []
        for k, vs in request.args.items():
            for v in vs:
                pairs.append((k, v))
        q = queryFromParams(pairs)
        t1 = time.time()
        result = iset.request(q)
        log.info('iset.request in %.1f ms', 1000 * (time.time() - t1))
        return json.dumps(result)

    run("0.0.0.0", networking.imageSet()[1])
Example #5
0
import sys
from klein import run, route
import json
sys.path.append("../..")
from db import getGraph
import auth

graph = getGraph()


@route('/allTags')
def allTags(request):
    tags = set()
    for row in graph.queryd(
            "SELECT ?tag WHERE { ?pic scot:hasTag [ rdfs:label ?tag ] }"):
        tag = unicode(row['tag'])
        if tag in auth.hiddenTags:
            continue
        tags.add(tag)
    tags = sorted(tags)
    return json.dumps({'tags': tags})


if __name__ == '__main__':
    run("0.0.0.0", 8054)
Example #6
0
for i in p:

    # Split recommendations into key of user id
    # and value of recommendations
    # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
    #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
    print(i)
    k, v = i.split('\t')

    # Put key, value into Redis
    r.set(k, v)


# Establish an endpoint that takes in user id in the path
@route('/<string:id>')
def recs(request, id):
    # Get recommendations for this user
    v = r.get(id)
    return 'The recommendations for user ' + str(id) + ' are ' + v.decode(
        "utf-8")


# Make a default endpoint
@route('/')
def home(request):
    return 'Please add a user id to the URL, e.g. http://localhost:8082/1234n'


# Start up a listener on port 8082
run("localhost", 8082)
Example #7
0
import sys
import os

sys.path.insert(
    0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'vendor')))

from twisted.web.http import NOT_FOUND, BAD_REQUEST

from klein import run, route

from zenlines import zenlines


@route("/", methods=["GET"])
def resource(request):
    letter = request.args.get("q", [None])[0]
    if not letter:
        request.setResponseCode(BAD_REQUEST)
        return "Bad Request"

    try:
        zenline = zenlines[letter]
    except KeyError:
        request.setResponseCode(NOT_FOUND)
        return "Not Found"

    return zenline


run("localhost", 8080, logFile=open(os.devnull, "w"))
    file_path = request.args[b'statement'][0]
    transactions = parse(file_path, parser_name)

    return json.dumps(transactions, indent=2, ensure_ascii=False)


def dump_balance(request, parser_name):
    def add_transaction_value(a, b):
        if isinstance(a, dict):
            a = a['value']
        return round(a + b['value'], 2)

    file_path = request.args[b'statement'][0]
    transactions = parse(file_path, parser_name)
    total = reduce(add_transaction_value, transactions)

    return json.dumps({'total': total}, indent=2, ensure_ascii=False)


@route('/<parser_name>')
def statement(request, parser_name):
    return dump_transactions(request, parser_name)


@route('/<parser_name>/balance')
def balance(request, parser_name):
    return dump_balance(request, parser_name)


run('0.0.0.0', 80)
Example #9
0
# -*- coding: utf-8 -*-
"""
    Created: 2016-12-27
    LastUpdate: 2016-12-27
    Filename: test_klein
    Description: 
    
"""
from klein import run, route


@route('/')
def home(request):
    return 'Hello, world'

@route('/user/<username>/test/<dataname>')
@route('/user/<username>')
def pg_user(request, username, dataname):
    return 'Hi %s!' % (username,)


@route('/user/bob')
def pg_user_bob(request):
    return 'Hello there 111!'



run('localhost', 8080)
Example #10
0
import sys
from klein import run, route
import json
sys.path.append("../..")
from db import getGraph
import auth

graph = getGraph()

@route('/allTags')
def allTags(request):
    tags = set()
    for row in graph.queryd(
            "SELECT ?tag WHERE { ?pic scot:hasTag [ rdfs:label ?tag ] }"):
        tag = unicode(row['tag'])
        if tag in auth.hiddenTags:
            continue
        tags.add(tag)
    tags = sorted(tags)
    return json.dumps({'tags': tags})

if __name__ == '__main__':
    run("0.0.0.0", 8054)
Example #11
0
        # add callback - when crawl is done cal return_items
        dfd.addCallback(self.return_items)
        return dfd

    def item_scraped(self, item, response, spider):
        self.items.append(item)

    def return_items(self, result):
        return self.items


def return_spider_output(output):
    """
    :param output: items scraped by CrawlerRunner
    :return: json with list of items
    """
    return json.dumps([dict(item) for item in output])


@route('/hepsiburada/<sku>')
def schedule(request, sku):
    request.setHeader('Content-Type', 'application/json')
    runner = MyCrawlerRunner()
    deferred = runner.crawl(HepsiBuradaSpider, sku=sku)
    deferred.addCallback(return_spider_output)
    return deferred


run("0.0.0.0", 8080)
Example #12
0
from klein import run
from hackle import *

if __name__ == "__main__":
    create_database_schema()
    connect_redis()
    setup_server_keys()
    run("localhost", 5000)
Example #13
0
def run():

    signal.signal(signal.SIGINT, signal.SIG_IGN)

    klein.run("localhost", 8080)
Example #14
0
File: app.py Project: melki/cours
from twisted.web.static import File
from klein import run, route

# @route('/slate/', branch=True)
# def static(request):
#     return File("./")

@route('/static/', branch=True)
def static(request):
    return File("./static")
    
@route('/slate')
def home(request):
    return File('index.html')

run("localhost", 2020)
Example #15
0
"""
    Stuart Powers
 
    This lets you browse by proxy arbitary domains:
 
    proxy www.google.com:   http://www.google.com.sente.cc:9055/
    proxy www.bing.com:     http://www.bing.com.sente.cc:9055/
    proxy xkcd.com:         http://xkcd.com.sente.cc:9055/
    
    This requires a DNS A record of '*' 
 
"""
 
from twisted.web.client import getPage
from klein import run, route
import sys
 
@route('/')
def sillyproxy(request):
 
    hs = request.getRequestHostname()
    proxy_host = hs.replace('.sente.cc','')
    return getPage('http://%s%s' % (proxy_host, request.uri))
 
 
run("0.0.0.0", 9055)
Example #16
0
# Load the recommendations into Redis
for i in p:

    # Split recommendations into key of user id
    # and value of recommendations
    # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
    #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
    k, v = i.split('t')

    # Put key, value into Redis
    r.set(k, v)


# Establish an endpoint that takes in user id in the path
@route('/<string:id>')
def recs(request, id):
    # Get recommendations for this user
    v = r.get(id)
    return 'The recommendations for user ' + str(id) + ' are ' + v.decode(
        "utf-8")


# Make a default endpoint
@route('/')
def home(request):
    return 'Please add a user id to the URL, e.g. http://localhost:8080/1234n'


# Start up a listener on port 8085
run("localhost", 8085)
Example #17
0
                postdata=urllib.urlencode({
                    'username': config['username'],
                    'remote_key': config['remote_key'],
                    }))
    token = json.loads(result)

    yield getPage(tasksUri(), method="POST",
                postdata=urllib.urlencode({
                    'token': token,
                    'task[content]': taskText,
                    'task[position]': 1,
                }))

@klein.route('/')
def index(request):
    return ('POST an email message to <a href="/newmail">newmail</a> '
            'to add a task. The email subject line becomes the task text.')
    
@klein.route('/newmail', methods=['POST'])
def newmail(request):
    msg = email.message_from_file(request.content)
    subject = msg['subject']
    if subject is None:
        raise ValueError("no subject found")
    
    done = postTask(subject)
    done.addCallback(lambda result: "ok")
    return done

klein.run('0.0.0.0', port=9108)
    return success(action)


@route('/list')
def list(request):
    action = 'list'
    global userdb
    for k, v in userdb.items():
        print "[%s:%s]" % (k, v)
    return success(action)


@route('/getkey')
def getkey(request):
    action = 'getkey'
    user = request.args.get('user')[0]
    if not user:
        return failure(action, request, 'did not send user param', 400)
    global userdb
    key = userdb.get(user)
    return json.dumps({action: True, 'key': key})


@route('/del', methods=['POST'])
def delete(request):
    action = 'del'
    return failure(action, request, 'not implemented', 500)


run(SERVER, PORT)
Example #19
0
 def run(self):
     reactor.addSystemEventTrigger('before', 'shutdown', stopLogging)
     klein.run(config.app_ip, config.app_port)
# Load the recommendations into Redis
for i in p:

  # Split recommendations into key of user id 
  # and value of recommendations
  # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
  #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
  k,v = i.split('\t')

  # Put key, value into Redis
  r.set(k,v)

# Establish an endpoint that takes in user id in the path
@route('/<string:id>')

def recs(request, id):
  # Get recommendations for this user
  v = r.get(id)
  return 'The recommendations for user '+id+' are '+v.decode('utf-8')


# Make a default endpoint
@route('/')

def home(request):
  return 'Please add a user id to the URL, e.g. http://localhost:8083/1234n'

# Start up a listener on port 8081
run("localhost", 8083)
Example #21
0

# Klein offers two helpers to start your server.  You really ought to
# pick one or the other of these, but I'm including both here for
# demonstration purposes.

if __name__ == '__main__':
    # For the simplest cases, you can use klein.run to start a web
    # server as soon as your script loads.
    from klein import run
    import os
    # Get the server port from the environment, or use default.
    port = int(os.environ.get('PORT', '8081'))

    # You tell it which network interface to listen on.  The empty string
    # '' will use all available interfaces.
    run('', port)

else:
    # klein.resource is a web.Resource you can use to refer to your
    # application from other Python modules, or used when starting
    # a server from the command line with twistd, like this:
    #
    # twistd -n web --class=kleindemo.main.resource
    #
    # twistd has an assortment of options for log files and
    # process management and other such useful things.

    #noinspection PyUnresolvedReferences
    from klein import resource
Example #22
0
            ur.write('\r\n')

        d = renderMessage(user.name, request.args['msg'][0], request)
        d.addCallback(writeEvent, updateRequest)

    return 'ok'


@route("/")
def index(request):
    user = request.getSession(IUser)

    if user.name == None:
        return LoginPage()
    else:
        return ChatPage()


@route("/login")
def login(request):
    session = request.getSession()
    user = IUser(session)
    user.name = request.args['name'][0]

    request.redirect("/")
    request.finish()


if __name__ == '__main__':
    run("localhost", 8080)
Example #23
0
        #content = '''
        #<html><body>%s<br>%s</body></html>
        #''' % (js_data['id'], js_data2['longUrl'])
        defer.returnValue(content)
    return callback()



@route('/url/', methods=['GET', 'POST'])
def entry_login(request):
    if request.method == 'GET':
        short_url = request.args.get('shortUrl', [None])[0]
        if not short_url:
            return 'require shortUrl'
        pr = urlparse.urlparse(short_url)
        path = pr.path.strip('/')
        path = path[ path.rfind('/') + 1 : ]

        return duan.get_long_url(path)
    if request.method == 'POST':
        long_url = request.args.get('longUrl', [None])[0]
        if not long_url:
            return 'require longUrl'
        return duan.insert_long_url(long_url)

    return 'Undefine method'



run('localhost', 8080, keyFile='private.pem', certFile='cacert.pem')
Example #24
0
File: rates.py Project: drewp/photo
        'byYear':  defaultdict(lambda: 0),
        'byDay':  defaultdict(lambda: 0),
    }

    for row in graph.queryd(
            """SELECT ?date WHERE {
                 ?pic a foaf:Image; dc:date ?date .
               }"""):
        date = datetime.date(*map(int, row['date'].split('-')))
        weekStart = date - datetime.timedelta(days=date.isoweekday())
        out['byWeek'][weekStart.isoformat()] += 1
        out['byDay'][row['date']] += 1
        out['byMonth'][row['date'].rsplit('-', 1)[0]] += 1
        out['byYear'][row['date'].rsplit('-', 2)[0]] += 1
    _rates = out
    return out
    
@route('/rates')
def rates(request):
    return json.dumps(getRates())

@route('/heatmap')
def heatmap(request):
    import heatmap
    reload(heatmap)
    request.setHeader('Content-Type', 'image/png')
    return heatmap.makeImage(getRates())

if __name__ == '__main__':
    run("0.0.0.0", 8045)
Example #25
0
import sys

from klein import run

from wedis import root


port = int(sys.argv[1]) if sys.argv[1:] else 8080


run("localhost", port)
Example #26
0
STATIC_DIR    = './webui/public/'
ELM_DEVSERVER = 'http://*****:*****@route('/track/')
def test(request):
    return CsvTsdb(DATAFILE).resource

# for development
@route('/dev/', branch=True)
def proxy_devserver(request):
    def stream_response(response):
        request.setResponseCode(response.code)
        for key, values in response.headers.getAllRawHeaders():
            for value in values:
                request.setHeader(key, value)
        d = treq.collect(response, request.write)
        d.addCallback(lambda _: request.finish())
        return d

    url = ELM_DEVSERVER.encode('utf-8') + request.uri[len('/dev'):]
    d = treq.request(request.method.decode('ascii'), url)
    d.addCallback(stream_response)
    return d

@route('/', branch=True)
def static_files(request):
    return File(STATIC_DIR)

if __name__ == '__main__':
    run("localhost", PORT)
Example #27
0
File: app.py Project: dc303/destiny
  return None

@klein.route('/robots.txt')
def robots(request):
  return None

@klein.route('/', branch=True)
def index(request):
  with open("index.html", "r") as f:
    return f.read()

def monkeypatch_klein_render(render):
  @wraps(render)
  def new_render(request):
    host = request.getRequestHostname()
    port = getattr(request.getHost(), "port", 80)
    secure = request.isSecure()
    request.setHost(host, port, secure)
    return render(request)
  return new_render


def resource():
  klein_resource = klein.resource()
  klein_resource.render = monkeypatch_klein_render(klein_resource.render)
  return klein_resource

if __name__ == "__main__":
  klein.run("localhost", 8080)

Example #28
0
def start_rest_server():
    run('localhost', 9898)
Example #29
0
    else:
        offset = 0

    if 'limit' in json:
        limit = get_json_arg(json, 'limit')
    else:
        limit = 20

    log.msg(start_time)
    log.msg(offset)
    log.msg(limit)

    result = db_connection.execute(text('SELECT users.user_name, messages.message_text, messages.message_time FROM messages '\
        'INNER JOIN message_tag ON message_tag.message_id = messages.id '\
        'INNER JOIN tags ON message_tag.tag_id = tags.id '\
        'INNER JOIN users ON messages.user_id = users.id '\
        'WHERE tags.tag_name = :tag_name '\
        'AND messages.message_time < :start_time '\
        'ORDER BY messages.message_time DESC '\
        'LIMIT :limit OFFSET :offset'),
        tag_name=tag_name, start_time=start_time, limit=limit, offset=offset).fetchall()

    log.msg(result)

    return [dict(r) for r in result]



if __name__ == '__main__':
    run(config.bind_address, config.bind_port)
    diet_label = 'balanced'
    #diet_label = 'low-fat'

    calorie = str(int(float(calorie)))
    calories = '1-' + calorie
    #calories = calorie
    print "received:", calories

    #APP_RECIPE_URL = 'https://api.edamam.com/search?q=&app_id={}&app_key={}&from=0&to=1&calories={}&diet={}'.format(APP_RECIPE_ID,APP_RECIPE_KEY,calories,diet_label)
    APP_RECIPE_URL = 'https://api.edamam.com/search?q={}&app_id={}&app_key={}&calories={}&diet={}'.format(
        choice, APP_RECIPE_ID, APP_RECIPE_KEY, calories, diet_label)
    r = requests.get(APP_RECIPE_URL)
    re = r.json()

    food_name = re['hits'][0]['recipe']['label']
    img = re['hits'][0]['recipe']['image']
    cal = str(re['hits'][0]['recipe']['calories'] /
              re['hits'][0]['recipe']['yield'])
    fat = str(re['hits'][0]['recipe']['totalNutrients']['FAT']['quantity'])
    protein = str(
        re['hits'][0]['recipe']['totalNutrients']['PROCNT']['quantity'])

    print calorie, 'received'
    print food_name, img, cal, fat, protein
    return json.dumps("{}#{}#{}#{}#{}".format(food_name, img, cal, fat,
                                              protein))
    #return "ok"


run("", 1203)
Example #31
0
import networking
from oneimagequery import photoCreated

graph = getGraph()

def findPhotos(graph):
    for row in graph.query("SELECT ?uri WHERE { ?uri a foaf:Image . }"):
        yield row.uri

def writeDoc(graph, uri, elasticRoot):
    t = photoCreated(graph, uri)
    fetch(elasticRoot + '')

@route('/update/all', method='POST')
def updateAll(request):
    for uri in findPhotos(graph):
        writeDoc(uri)

@route('/update', method='POST')
def updateOne(request):
    if request.args['uri']
        pics, elapsed = timed(lambda: list(itertools.islice(newestPics(graph), 0, 3)))
        return json.dumps({"newest": pics,
                           "profile": {"newestPics": elapsed}})
    else:
        raise NotImplementedError()



run("0.0.0.0", 8036)
    "startup": ""
}


@route('/', branch=False)
def static(request):
    return File("../../WebUI/SandTableUI")


@route('/getsettings', branch=False)
def getsettings(request):
    return json.dumps(stSettings)


@route('/postsettings', methods=['POST'])
def postsettings(request):
    global stSettings
    postData = json.loads(request.content.read().decode('utf-8'))
    print(postData)
    stSettings = postData
    return succeed(None)


@route('/exec/<string:argToExec>', branch=False)
def execute(request, argToExec):
    print("Execute ", argToExec)
    return succeed(None)


run("localhost", 9027)
Example #33
0
        license = self.get_license(data)
        license = license.replace(' ', '_')
        return self.write_shield(license, 'blue')


generators = {
    'd': DownloadHandler,
    'download': DownloadHandler,
    'v': VersionHandler,
    'version': VersionHandler,
    'wheel': WheelHandler,
    'egg': EggHandler,
    'license': LicenseHandler,
    'format': FormatHandler,
}


@route('/<string:generator>/<string:package>/badge.<string:extension>')
def shield(request, generator, package, extension):
    klass = generators[generator]()
    img = klass.get(request, package, extension)
    ext = mimetypes.types_map[".{0}".format(extension)]
    request.headers.update({'content-type': ext})
    return img.read()


if __name__ == '__main__':
    if '.svg' not in mimetypes.types_map:
        mimetypes.add_type("image/svg+xml", ".svg")
    run("localhost", 8888)
Example #34
0
from klein import run, route


@route('/')
def home(request):

    print(request.content.read())
    return 'Hello, world!'


run("127.0.0.1", 8136)
Example #35
0
                bb.setBacklight(min(255, median // 4))
        if 'keyDown' in self.last:
            keyNum = self.last['keyDown']
            sendOneShot((ROOM['ariBed/button%s' % keyNum],
                         ROOM['change'],
                         ROOM['down']))
        if self.last['motion']:
            bb.sendIr('led_22_key', 'ON')
        else:
            bb.sendIr('led_22_key', 'OFF')


@klein.route('/graph', methods=['GET'])
def getGraph(request):
    g = StateGraph(ROOM.busybox)
    g.add((ROOM.busybox, ROOM.localHour, Literal('x')))
    for attr in ['slider1', 'slider2', 'slider3', 'slider4']:
        # needs: smoothing, exp curve correction
        g.add((ROOM['busybox/%s' % attr], ROOM.value, Literal(round(poller.last[attr] / 1021, 3))))
    g.add((ROOM['busybox/motion'], ROOM.value, Literal(poller.last['motion'])))
    request.setHeader('Content-type', 'application/x-trig')
    return g.asTrig()

poller = Poller()
task.LoopingCall(poller.poll).start(.05)

# todo: watch reasoning graph. put lines on display. send updated ir codes.

klein.run('0.0.0.0', port=9056)

Example #36
0
# Load the recommendations into Redis
for i in p:

  # Split recommendations into key of user id 
  # and value of recommendations
  # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
  #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
  k,v = i.split('t')

  # Put key, value into Redis
  r.set(k,v)

# Establish an endpoint that takes in user id in the path
@route('/<string:id>')

def recs(request, id):
  # Get recommendations for this user
  v = r.get(id)
  return 'The recommendations for user '+id+' are '+v


# Make a default endpoint
@route('/')

def home(request):
  return 'Please add a user id to the URL, e.g. http://localhost:8080/1234n'

# Start up a listener on port 8080
run("localhost", 8080)
   
Example #37
0
                    titles_cache.append(p.Title)
                    places[id] = p

    # Some sources may already have set the location. Filter those out and get the geopoints
    geopoints = yield geo.address_to_geopoint({l.Id:l.Address
                                               for l in places.values()
                                               if l.Location is None})

    for id,point in geopoints.items():
        places[id] = places[id]._replace(Location=point)

    for id,place in places.items():

        if not place.Distance and not place.Location:
            # We have a problem! For now exclude them from the results.
            # ToDo: Do something smart here.
            continue

        returner.append(place._replace(Distance=geo.distance(location.geopoint, place.Location)))

    # Now each location hopefully has a resolved GeoPoint we can sort the Locations by the distance from us
    returner = [p._asdict() for p in sorted(returner, key=operator.attrgetter('Distance'))[:10]]

    t2 = time.time()
    print "Request took %s"%(t2-t1)
    request.setHeader("content-type", "application/json")
    defer.returnValue(json.dumps(returner))

if "--run" in sys.argv:
    run("",8080)
Example #38
0
# Load the recommendations into Redis
for i in p:

    # Split recommendations into key of user id
    # and value of recommendations
    # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
    #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
    k, v = i.split('\t')
    #print(i)
    # Put key, value into Redis
    r.set(k, v)


# Establish an endpoint that takes in user id in the path
@route('/<string:id>')
def recs(request, id):
    # Get recommendations for this user
    v = r.get(id)
    return 'The recommendations are ' + v.decode('utf-8')


# Make a default endpoint
@route('/')
def home(request):
    return 'Please add a user id to the URL, e.g. http://localhost:8090/1234n'


# Start up a listener on port 8090
run("localhost", 8090)
Example #39
0
# Load the recommendations into Redis
for i in p:

    # Split recommendations into key of user id
    # and value of recommendations
    # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
    #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
    k, v = i.split()

    # Put key, value into Redis
    r.set(k, v)


# Establish an endpoint that takes in user id in the path
@route('/<string:id>')
def recs(request, id):
    # Get recommendations for this user
    v = r.get(id)
    return 'The recommendations for user ' + id + ' are ' + v


# Make a default endpoint
@route('/')
def home(request):
    return 'Please add a user id to the URL, e.g. http://localhost:8080/1234n'


# Start up a listener on port 8080
run("localhost", 3080)
Example #40
0
    calorie2 = calorie2 / serving_weight_grams2 * weight2
    fat2 = fat2 / serving_weight_grams2 * weight2
    protein2 = protein2 / serving_weight_grams2 * weight2

    calorie3 = calorie3 / serving_weight_grams3 * weight3
    fat3 = fat3 / serving_weight_grams3 * weight3
    protein3 = protein3 / serving_weight_grams3 * weight3

    timestamp = imageName[:-5].split(' ')

    ret = {"weights":[weight1,weight2,weight3],"day":timestamp[1],"hour":timestamp[2],"minute":timestamp[3],"second":timestamp[4]}
    db.ret.insert_one(ret)





    #label1 = food_name1 + str(calorie1) + str(fat1) + str(protein1) +"per" +str(serving_weight_grams1)
    #label2 = food_name2 + str(calorie2) + str(fat2) + str(protein2) +"per" +str(serving_weight_grams2)
    #label3 = food_name3 + str(calorie3) + str(fat3) + str(protein3) +"per" +str(serving_weight_grams3)
    #label1 = "{}:\n{}Cal\nfat{}g\nprotein{}g\nper{}\n".format(food_name1, calorie1, fat1, protein1, serving_weight_grams1)
    #label2 = "{}:\n{}Cal\nfat{}g\nprotein{}g\nper{}\n".format(food_name2, calorie2, fat2, protein2, serving_weight_grams2)
    #label3 = "{}:\n{}Cal\nfat{}g\nprotein{}g\nper{}\n".format(food_name3, calorie3, fat3, protein3, serving_weight_grams3)
    #label1 = "{}:\n{}Cal\nfat{}g\nprotein{}g\n".format(food_name1, calorie1, fat1, protein1)
    #label2 = "{}:\n{}Cal\nfat{}g\nprotein{}g\n".format(food_name2, calorie2, fat2, protein2)
    #label3 = "{}:\n{}Cal\nfat{}g\nprotein{}g\n".format(food_name3, calorie3, fat3, protein3)

    return 'Complete!#{}#{}#{}#{}#{}#{}#{}#{}#{}#{}#{}#{}'.format(food_name1, calorie1, fat1, protein1,food_name2, calorie2, fat2, protein2,food_name3, calorie3, fat3, protein3)

run("", 1021)
Example #41
0
from redis import Redis
from klein import run, route


@route('/')
def home(request):
    return 'Hello, world!'


@route('/redis')
def redis(request):
    client = Redis.from_url("redis://redis/0")
    redis_working = client.ping()
    response = ''
    if redis_working:
        response = 'PONG'
    else:
        raise BaseException('Redis not working properly.')

    return 'Sent PING server -> Redis. <br/> Received ' + response + ' server <- Redis.'


run("0.0.0.0", 5000)
Example #42
0
def main():
    run("", 8081)
Example #43
0
            stmts.append((newAltUri, PHO[k], Literal(v)))

    graph.add(stmts, context=ctx)
    return "added %s statements to context %s" % (len(stmts), ctx)


def pickNewUri(self, uri, tag):
    for suffix in itertools.count(1):
        proposed = URIRef("%s/alt/%s%s" % (uri, tag, suffix))
        if not graph.contains((proposed, None, None)):
            return proposed


def personAgeString(isoBirthday, photoDate):
    try:
        sec = iso8601.parse(str(photoDate))
    except Exception:
        sec = iso8601.parse(str(photoDate) + '-0700')

    birth = iso8601.parse(isoBirthday)
    days = (sec - birth) / 86400
    if days / 30 < 12:
        return "%.1f months" % (days / 30)
    else:
        return "%.1f years" % (days / 365)


if __name__ == '__main__':
    graph = db.getGraph()
    run('0.0.0.0', networking.oneImageServer()[1])
Example #44
0
# Load the recommendations into Redis
for i in p:

  # Split recommendations into key of user id
  # and value of recommendations
  # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
  #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
  k,v = i.split('\t')
  #print(k)

  # Put key, value into Redis
  r.set(k,v)

# Establish an endpoint that takes in user id in the path
@route('/<string:id>')

def recs(request, id):
  # Get recommendations for this user
  v = r.get(id)
  return 'The recommendations for user '+id+' are '+v.decode("utf-8")


# Make a default endpoint
@route('/')

def home(request):
  return 'Please add a user id to the URL, e.g. http://localhost:8080/1234n'

# Start up a listener on port 8081
run("localhost", 8081)
Example #45
0
# Load the recommendations into Redis
for i in p:

    # Split recommendations into key of user id
    # and value of recommendations
    # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
    #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
    k, v = i.split()

    # Put key, value into Redis
    r.set(k, v)


# Establish an endpoint that takes in user id in the path
@route('/<string:id>')
def recs(request, id):
    # Get recommendations for this user
    v = r.get(id)
    return 'The recommendations for user ' + id + ' are ' + v


# Make a default endpoint
@route('/')
def home(request):
    return 'Please add a user id to the URL, e.g. http://localhost:8080/1234n'


# Start up a listener on port 8080
run("localhost", 6370)
Example #46
0
_sfdcToken = "yourSalesforceSecurityToken"
_sfdcSandbox = True

# Setup Fulcrum Webooks to hit http://yourdomain.com/_routeURL
_routeURI = 'fulcrumApp/webHook/Receipt'


### Web sever accept
@route('/' + _routeURI, methods=['POST'])
def do_post(request):
    content = json.loads(request.content.read())
    print request.content.read()

    if content['type'] == 'form.create':
        print 'Form Create'
        #Connect to Salesforce
        fulcrumToSalesforce = fatso.FulcrumApplicationToSalesforceObject()
        #Create Object
        fulcrumToSalesforce.construct_fulcrum_sfdc_object(
            content['data'], 'create')
    elif content['type'] == 'form.update':
        print 'Form Update'
        fulcrumToSalesforce = fatso.FulcrumApplicationToSalesforceObject()
        fulcrumToSalesforce.construct_fulcrum_sfdc_object(
            content['data'], 'create')
        fulcrumToSalesforce.construct_fulcrum_sfdc_object(
            content['data'], 'update')


run('0.0.0.0', _webhookServerPort)
Example #47
0
# Load the recommendations into Redis
for i in p:

  # Split recommendations into key of user id 
  # and value of recommendations
  # E.g., 35^I[2067:5.0,17:5.0,1041:5.0,2068:5.0,2087:5.0,
  #       1036:5.0,900:5.0,1:5.0,081:5.0,3135:5.0]$
  a = str(i).split()

  # Put key, value into Redis
  r.set(a[0],a[1])

# Establish an endpoint that takes in user id in the path
@route('/<string:id>')

def recs(request, id):
  # Get recommendations for this user
  v = r.get(id)
  return 'The recommendations for user '+id+' are '+v.decode("utf-8")+'\n'


# Make a default endpoint
@route('/')

def home(request):
  return 'Please add a user id to the URL, e.g. http://localhost:4200/30'

# Start up a listener on port 4200
run("localhost", 4200)
Example #48
0
            stmts.append((newAltUri, PHO[k], Literal(v)))

    graph.add(stmts, context=ctx)
    return "added %s statements to context %s" % (len(stmts), ctx)

def pickNewUri(self, uri, tag):
    for suffix in itertools.count(1):
        proposed = URIRef("%s/alt/%s%s" % (uri, tag, suffix))
        if not graph.contains((proposed, None, None)):
            return proposed
                


def personAgeString(isoBirthday, photoDate):
    try:
        sec = iso8601.parse(str(photoDate))
    except Exception:
        sec = iso8601.parse(str(photoDate) + '-0700')

    birth = iso8601.parse(isoBirthday)
    days = (sec - birth) / 86400
    if days / 30 < 12:
        return "%.1f months" % (days / 30)
    else:
        return "%.1f years" % (days / 365)

if __name__ == '__main__':
    graph = db.getGraph()
    run('0.0.0.0', networking.oneImageServer()[1])

Example #49
0
File: chat.py Project: drewp/magma
port = 8011
loginPage = 'https://bigasterisk.com/chat/login?redir=https://bigasterisk.com/chat/'
        
factory = WebSocketServerFactory(u"ws://127.0.0.1:%s" % port)
factory.protocol = MessagesSocketProtocol
resource = WebSocketResource(factory)

@klein.route('/messages')
def ws(request):
    return resource

@klein.route('/', branch=True)
def root(request):
    if not request.getHeader('x-foaf-agent'):
        request.setResponseCode(307)
        request.setHeader('location', loginPage)
        return
    
    if b'.' not in request.path:
        print('%r appears to be a polymer route' % request.path)
        request.path = b'/'
        request.uri = b'/'
        request.postpath = [b'']
    root = b'./'
    if os.path.exists(b'build/es6-bundled%s' % request.path):
        return File('./build/es6-bundled/')
    return File('./')

klein.run('0.0.0.0', port)