Exemple #1
0
def job():
    #initiate workers for a new job
    hash = request.arges.get('hash')
    hashtype = request.args.get('type')
    share = request.args('share')
    capacity = request.args('cap')
    return 'Running /job'
Exemple #2
0
def ruta_automovil():
    param1 = request.args('inicio')
    param2 = request.args('fin')
    js = shortest_pathAvion(param1, param2)

    resp = Response(js, status=200, mimetype='application/json')
    resp.headers['Link'] = 'http://sistra.com'

    return resp
Exemple #3
0
def login2():
    loginUsername = request.args('username')
    loginPassword = request.args('passwrd')

    print loginPassword, loginUsername

    loginDAO = LoginDao()
    obj = loginDAO.LogDAO(loginUsername, loginPassword)
    if len(obj) != 0:
        render_template('/home')
    else:
        render_template('/')
        def handler():
            if not self.check_signature(
                    request.args.get('timestamp', ''),
                    request.args.get('nonce', ''),
                    request.args.get('signature', '')
            ):
                return 'Invalid Request.'
            if request.method == 'GET':
                return request.args('echostr')

            body = request.data
            message = parse_user_msg(body)
            # get_reply() return the reply object for given message
            reply = self.get_reply(message)
            if not reply:
                return ''
            # flask将视图函数的返回值自动转为一个响应对像. 如果返回值是一个字符串
            # 它将被转换为以该字符串为主体的, 状态码为200, MIME类型是 text/html的响应对像.
            # flask 把返回值转为响应对像的逻辑如下:
            #   1. 如果返回值是一个合法的响应对像, 它会从视图直接返回
            #   2. 如果返回的是一个字符串, 响应对像会用字符串数据和默认参数创建
            #   3. 如果返回的是一个元组, 且元组中的元素可以提供额外的信息.
            #      这样的元组必须是 (response, status, headers) 形式, 且至少包含一个元素.
            #      status值会覆盖状态代码, headers可以是一个列表或者字典, 做为额外的消息标头值
            #   4. 如果上述条件均不满足, flask假设返回值是一个合法的WSGI应用程序,
            #      并转换为一个请求对像
            # 如果想在视图中操纵上述步骤结果的响应对像, 可以使用make_response()函数
            response = make_response(create_reply(reply, message=message))
            response.headers['content_type'] = 'application/xml'
            return response
Exemple #5
0
def update():
    (db, table) = get_table(request)
    keyed = hasattr(db[table],'_primarykey')
    record = None
    if keyed:
        key = [f for f in request.vars if f in db[table]._primarykey]
        if key:
            record = db(db[table][key[0]] == request.vars[key[0]], ignore_common_filters=True).select().first()
    else:
        record = db(db[table].id == request.args(2),ignore_common_filters=True).select().first()

    if not record:
        qry = query_by_table_type(table, db)
        session.flash = T('record does not exist')
        redirect(URL('select', args=request.args[:1],
                     vars=dict(query=qry)))

    if keyed:
        for k in db[table]._primarykey:
            db[table][k].writable=False

    form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'),
                   ignore_rw=ignore_rw and not keyed,
                   linkto=URL('select',
                   args=request.args[:1]), upload=URL(r=request,
                   f='download', args=request.args[:1]))

    if form.accepts(request.vars, session):
        session.flash = T('done!')
        qry = query_by_table_type(table, db)
        redirect(URL('select', args=request.args[:1],
                 vars=dict(query=qry)))
    return dict(form=form,table=db[table])
Exemple #6
0
def update():
    (db, table) = get_table(request)
    keyed = hasattr(db[table], '_primarykey')
    record = None
    if keyed:
        key = [f for f in request.vars if f in db[table]._primarykey]
        if key:
            record = db(db[table][key[0]] == request.vars[key[0]],
                        ignore_common_filters=True).select().first()
    else:
        record = db(db[table].id == request.args(2),
                    ignore_common_filters=True).select().first()

    if not record:
        qry = query_by_table_type(table, db)
        session.flash = T('record does not exist')
        redirect(URL('select', args=request.args[:1], vars=dict(query=qry)))

    if keyed:
        for k in db[table]._primarykey:
            db[table][k].writable = False

    form = SQLFORM(db[table],
                   record,
                   deletable=True,
                   delete_label=T('Check to delete'),
                   ignore_rw=ignore_rw and not keyed,
                   linkto=URL('select', args=request.args[:1]),
                   upload=URL(r=request, f='download', args=request.args[:1]))

    if form.accepts(request.vars, session):
        session.flash = T('done!')
        qry = query_by_table_type(table, db)
        redirect(URL('select', args=request.args[:1], vars=dict(query=qry)))
    return dict(form=form, table=db[table])
Exemple #7
0
    def get(self):
        try:
            role_id = request.args[K_ROLE_ID]
        except BaseException:
            role_id = None
        try:
            role_name = request.args(K_ROLE_NAME)
        except BaseException:
            role_name = None

        role = model.Role.query.filter(
            model.Role.id == role_id if role_id is not None else text(''),
            model.Role.role_name == role_name
            if role_name is not None else text('')).first()

        if role is not None:
            return {
                'message': '',
                K_ROLE_ID: role.id,
                K_ROLE_NAME: role.role_name,
                K_ROLE_DESCRIPTION: role.description,
                'privilege_list': role.privileges
            }
        else:
            return {'message': 'No such role'}
Exemple #8
0
def remove_team_batch():
    ids = [int(x) for x in request.args('id').split(',')]
    db.session.query(Teams).filter(Teams.id.in_(ids)).delete()
    db.session.commit()
    for id in ids:
        redis_store.hdel('teams', id)
    return jsonify({'message': '删除成功', 'type': 'success'})
def reRunEvent():
    @after_this_request
    def add_header(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response

    if 'eventName' not in request.args:
        return flask.make_response(
            '{\"text\":"Argument \'eventName\' not in request"}', 400)
    if 'eventTime' not in request.args:
        sentTime = request.args('eventTime')
    else:
        sentTime = None
    if 'eventType' not in request.args:
        return flask.make_response(
            '{\"text\":"Argument \'eventType\' not in request"}', 400)
    if 'eventSender' not in request.args:
        return flask.make_response(
            '{\"text\":"Argument \'eventSender\' not in request"}', 400)
    if 'eventData' not in request.args:
        return flask.make_response(
            '{\"text\":"Argument \'eventData\' not in request"}', 400)

    return reRunEvent_handler(request.args['eventName'], sentTime,
                              request.args['eventType'],
                              request.args['eventSender'],
                              request.args['eventData'])
Exemple #10
0
def signup():
	err = request.args('error',)
	if request.method == 'POST':
		unique_user = db['Users'].find({ 'username': { '$exists': True, '$in': [ str(request.form['username']) ]}})
		if unique_user.count() == 0:
			if request.form['password'] == request.form['password2']:
				user = {}
				for key,val in request.form.items():
					if 'password' == key:
						user['password'] = pbkdf2_sha256.hash(val)
					elif 'password2'== key:
						pass
					else:
						user[key] = val

				session['username'] = str(request.form['username'])
				session['logged_in'] = False
				try:
					db['Users'].insert_one(user)
				except Exception as e:
					err = 'Users cant be signed up.' + e
					return render_template('signup.html', error=err)    

				return redirect(url_for('home'))
			else:
				err = 'Passwords do not match.'
				return render_template('signup.html', error=err)
		else:
			err = 'Users not exists try again!'
			return render_template('signup.html', error=err)
	return render_template('signup.html')
Exemple #11
0
def img_upload():
    try:
        print(request.get('image'))
        print(request.args('image'))
        print(request.form('image'))
    except:
        print('your code sucks :(')
    imgfile = request.files['image'].read()
    image = types.Image(content=imgfile)
    gcv_response = client.label_detection(image=image)
    labels = gcv_response.label_annotations
    response_dictionary = {}
    for label in labels:
        tag = label.description
        response_dictionary[tag] = label.score
    img_keywords = [label.description for label in labels]
    bestfoldermatch = get_match(response_dictionary)
    if (bestfoldermatch is None):
        message = 'Here are some relevant keywords for your image:<br/>'
        message += ' | '.join(img_keywords)
    else:
        message = 'Is this ' + bestfoldermatch + '?'
    response = {'message': message}
    #random_image = get_random_image(bestfoldermatch)
    #response['image'] = random_image
    # return jsonify(response_dictionary)
    print response_dictionary
    #    return jsonify(response)
    return render_template('response.html', message=response['message'])
def test3333():
    print "test======================================================="
    ip = request.args(type=unicode)
    print(ip)
    print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
    ip2 = ip.to_dict()
    ip3 = ip2['ename']
    print (ip3)
Exemple #13
0
def search():
    query = request.args("search")
    form = SearchForm()
    # if form.validate_on_submit():
    #     flash(f"Searching for {form.search.data}!")
    #     #return redirect(url_for("home"))
    # print(form.__dict__)
    return render("search.jinja", title="search", form=form, query=query)
Exemple #14
0
def create():
    """gets the json object and creates the document from the provided type and id. returns 200 if ok else 500"""
    d = request.args().to_dict()
    data = request.get_json()
    try:
        cloudFireStore.create(data, **d)
        resp = jsonify(success=True)
        return resp
    except:
        raise InternalServerError(
            "The requested operation could not be performed")
def get_filterscore():
    if "desc" in request.args and request.args.get("desc") == "False":
        if 'avgscore1' in request.args:
            avgscore1 = request.args.get("avgscore1")
        else:
            avgscore1 = 5
        if 'avgscore2' in request.args:
            avgscore2 = request.args.get("avgscore2")
        else:
            avgscore2 = 5
        if 'avgscore3' in request.args:
            avgscore3 = request.args.get("avgscore3")
        else:
            avgscore3 = 5
        if "cid" in request.args:
            cid = request.args.get("cid")
            course = Course.query.filter_by(cid=cid)
            cname = course.name
        else:
            cname = request.args("cname")
        temp = Review.query.with_entities(Review.cname,Review.pname).\
            group_by(Review.cname,Review.pname).\
                having(db.and_(db.func.avg(Review.score1) <= avgscore1,
                db.func.avg(Review.score2) <= avgscore2,
                db.func.avg(Review.score3) <= avgscore3)).subquery()
        review = Review.query.filter(Review.cname==temp.c.cname,Review.pname==temp.c.pname,Review.cname==cname)
        return jsonify([r.serialize() for r in review])
    else:
        if 'avgscore1' in request.args:
            avgscore1 = request.args.get("avgscore1")
        else:
            avgscore1 = 0
        if 'avgscore2' in request.args:
            avgscore2 = request.args.get("avgscore2")
        else:
            avgscore2 = 0
        if 'avgscore3' in request.args:
            avgscore3 = request.args.get("avgscore3")
        else:
            avgscore3 = 0
        if "cid" in request.args:
            cid = request.args.get("cid")
            course = Course.query.filter_by(cid=cid).first()
            cname = course.name
        else:
            cname = request.args.get("cname")
        temp = Review.query.with_entities(Review.cname,Review.pname).\
            group_by(Review.cname,Review.pname).\
                having(db.and_(db.func.avg(Review.score1) >= avgscore1,
                db.func.avg(Review.score2) >= avgscore2,
                db.func.avg(Review.score3) >= avgscore3)).subquery()
        review = Review.query.filter(Review.cname==temp.c.cname,Review.pname==temp.c.pname,Review.cname==cname)
        return jsonify([r.serialize() for r in review])
Exemple #16
0
def getCourses():
    if 'course_code' in request.args():
        course_code = request.args.get('course_code')
        if db.session.query(
                db.exists().where(Course.code == course_code)).scalar():
            course = db.session.query(Course).filter(
                Course.code == course_code).first()
            return jsonify(course.serialize())
        else:
            return "Error: Course not found"
    else:
        courses = Course.query.all()
        return jsonify([c.serialize() for c in courses])
Exemple #17
0
def get_characters():
    if request.method == 'GET':
        # When this method is called send back a json object of the characters
        # request.args key value pair
        # a request should look like http://localhost:5000/get_characters?user_id=1234
        characters = Character.query.filter_by(
            user=request.args('user_id').all())

        return jsonify(characters=characters)

    else:
        return json.dumps({'success': False}), 400, {
            'ContentType': 'application/json'
        }
Exemple #18
0
def analyse_tweets():
    query = request.args["query"]

    if "count" in request.args:
        count = int(request.args("count"))
    else:
        count = 10

    conf = json.load(open(config_path, "r"))

    analyzer = TweetsAnalyzer(config=conf)
    df = analyzer.analyze(query=query, count=count)

    return str(df["sentiment"].value_counts())
Exemple #19
0
def sendGroups():
    if not request.args:
        objs = os.listdir('groups')
        objs = [x for x in objs if x.startswith('group')]
        num = len(objs)
        s = str(num) + ','
        for name in objs:
            print(name)
            f = open("groups/" + name, 'r').read()
            elems = f.split('|')
            s = s + elems[0] + ':' + name + ','
        print(s)
        return s
    elif 'del' in request.args.keys():
        obj = request.args('del')
        os.remove('groups/' + obj)
        return "OK"
Exemple #20
0
def coursestudents(cid):
    cur = mysql.connection.cursor()
    if request.method=='POST':
        uid = request.args('name')
        if len(uid) in range(9, 12) and uid[:4] in ['6200', '9780']:
            flash ('student ID format is incorrect')
            return redirect(url_for('coursestudents', cid = cid))
            
        flash(addstudent(cid, uid))
        return redirect(url_for('coursestudents', cid = cid))
    students =[]
    ccid =cid[3:11]
    cur.execute("select user_id from enroll where course_id = %s;", [ccid])
    for row in cur.fetchall():
        students.append(row[0])
    print students, 'here'
    return render_template('lecturer-students.html', students = students, cid = cid)
Exemple #21
0
def get_activites():
    username = None
    if request.args:
        username = request.args("username", None)
    result = []
    if username:
        activity_iter = mydb.activity.find({
            "user_id": username
        }).sort("time_stamp", -1).limit(20)
        for activity in activity_iter:
            result.append(activity)
    else:
        activity_iter = mydb.activity.find().sort("time_stamp", -1).limit(20)
        for activity in activity_iter:
            activity["_id"] = "[HIDDEN]"
            result.append(activity)
    return jsonify({"activities": result})
Exemple #22
0
def edit():
    ''' The function pre-populates the data from the note instance
        that has been requested to be edited and renders it,
        once client sends in some data, it saves it in the database.'''

    note = db.notes(request.args(0)) or redirect(URL('error'))
    form = SQLFORM(db.notes, note, deletable=True)
    if form.validate():
        if form.deleted:
            db(db.notes.id == note.id).delete()
            redirect(URL('index'))
        else:
            note.update_record(**dict(form.vars))
            response.flash = 'records changed'
    else:
        response.flash = 'Something went wrong!'
    return dict(form=form)
Exemple #23
0
def edit():

    ''' The function pre-populates the data from the note instance
        that has been requested to be edited and renders it,
        once client sends in some data, it saves it in the database.'''
        
    note = db.notes(request.args(0)) or redirect(URL('error'))
    form=SQLFORM(db.notes, note, deletable = True)
    if form.validate():
        if form.deleted:
            db(db.notes.id==note.id).delete()
            redirect(URL('index'))
        else:
            note.update_record(**dict(form.vars))
            response.flash = 'records changed'
    else:
        response.flash = 'Something went wrong!'
    return dict(form=form)    
Exemple #24
0
def product_add():

    err_msg = None
    if request.method.lower() == "post":
        if dao.add_products(**dict(request.form)):
            return redirect(url_for('product-add.html'))
        else:
            err_msg = "Wrong!"

        categories = dao.read_categories()
        product = None
        if request.args.get("product_id"):
            product = dao.read_product_by_id(product_id=request.args("product_id"))

        return redirect(url_for('product-add.html'))

    categories = dao.read_categories()
    return render_template("product-add.html", categories=categories)
Exemple #25
0
def post_or_get_publication_files(pid):
  token = request.headers.get('Authorization') or request.args('token')
  if token != None and valid(token):                         
      payload = decode(token, JWT_SECRET)
      status = 200

      if request.method == 'POST':
        f = request.files.get('file')

        if f is None or f.filename == '':
          return HALResponse(response=document.Document(data={'message': 'Error - no file provided'}).to_json(), status=400, mimetype="application/hal+json")

        fid, content_type = str(uuid4()), f.content_type
        redis_files.hset(pid, fid, f.filename)
        redis_files.hset("files", fid, f.read())
        redis_files.hset("content_types", fid, content_type)
        f.close()

        data = {'message': 'File uploaded'}
        status = 201

      elif request.method == 'GET':
        files = redis_files.hgetall(pid)

        if files != None:
          data = {'files': json.dumps(files)}
        else:
          data = {'files': json.dumps([])}
  
      files = redis_files.hgetall(pid)
      
      api_links=link.Collection()

      for pub_file in files:
        l = link.Link(pub_file, 'http://api:5000/publications/' + pid + '/files/' + pub_file)
        l.name = "download_or_delete_file"
        api_links.append(l)

      return HALResponse(response=document.Document(data=data
                                  ,links=api_links).to_json(), status=status, mimetype="application/hal+json")

  else:
      return HALResponse(response=document.Document(data={'message': 'Invalid token - please try again'}).to_json(), status=401, mimetype="application/hal+json")
Exemple #26
0
def get_user_order():
    """
	查询用户信息
	GET请求
	:return:
	"""
    # 获取用户id
    user_id = g.user_id
    # 获取用户点击的是“我的订单” 还是”用户订单“参数
    # 用户的身份,用户想要查询作为房客预订别人房子的订单,还是想要作为房东查询别人预订自己房子的订单
    role = request.args("role", "")

    # 查询订单信息
    try:
        # 如果是房主(客户订单)
        if "landlord" == role:
            # 以房东的身份查询,先查询自己的房子有哪些
            houses = House.query.filter(House.user_id == user_id).all()
            houses_ids = [house.id for house in houses]  # 遍历取出所有房子id
            # 在查询预定了自己房子的订单
            orders = Order.query.filter(
                Order.house_id.in_(houses_ids)).order_by(
                    Order.create_time.desc()).all()
        else:
            # 否则是客户(显示我的订单)
            orders = Order.query.filter(Order.user_id == user_id).order_by(
                Order.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="订单查询失败!")

    # 将数据转换为字典
    orders_dict_list = []
    if orders:
        for order in orders:
            orders_dict_list.append(order.to_dict())
    # 返回结果
    return jsonify(errno=RET.OK,
                   errmsg="OK",
                   data={"orders": orders_dict_list})
Exemple #27
0
def create_chat():
    """
    Create a chat for a given user_id
    """
    chat = Chat.from_dict(request.json)
    chat_user = ChatUser.from_dict(request.json, request.args(['user_id']))
    query_1 = db.session.execute(
        '''
        INSERT INTO chats (name)
        VALUES (name)
        RETURNING id
        ON CONFLICT DO NOTHING
        '''
        , dict(name=chat.name)
    )
    
    query_2 = db.session.execute(
        '''
        INSERT INTO chat_users (user_id, chat_id)
        VALUES (:user_id, :chat_id)
        '''
        , dict(user_id=request.args['user_id'], chat_id=1)
    )
    db.session.commit()
Exemple #28
0
def index():
    if 'img' in request.args:  # return a dictionary
        img = request.args('img')
        og_image = url_for('static', filename='img', _external=True)
        og_url = url_for('index', _external=True)
    else:
        description = """Toi, tu sais comment utiliser la console, t'es jamais 
					à court d'idées pour réaliser ton objectif, tu es déterminé-e et
					et persévérant. Tes amis disent d'ailleurs volontier que 
					tu as du caracctère et que tu ne te laisses pas marcher sur 
					les pieds. un peu hacker sur les bords, tu aimes trouver des 
					solutions à tout problème. N'aurais-tu pas un petit problème 
					d'autorité?"""

        og_image = url_for('static', filename='tmp/sample.jpg', _external=True)
        og_url = url_for('index', _external=True)

    return render_template('index.html',
                           user_name='Julien',
                           user_image=url_for('static',
                                              filename='img/profile.png'),
                           description=description,
                           blur=True,
                           og_url=og_url)
Exemple #29
0
def read():
    language = request.args("lang")
    jobs = ro_jobs(language) + so_jobs(language) + wr_jobs(language)

    render_template("read.html", jobs=jobs)
Exemple #30
0
def pong():
    pingpong = request.args('ping')  # 이것을 써도 되지만 에러를 확인하고 싶어서 아랫줄처럼 사용한다.
    pingpong = request.args.get(
        'ping')  # flask에서는 .get('')로 dictionary처럼 받지만, list나 dict은 아니다.
    msg = request.args.get('msg')
    return render_template('pong.html', pingpong=pingpong, msg=msg)
Exemple #31
0
def malac():
    i1 = request.args(i1)
    i2 = request.args(i2)
    print(i1, i2)
    return(f'{i1}   {i2}')
Exemple #32
0
def login_confirm():
    data = request.args()

    return
Exemple #33
0
def search():
    post = request.args('search')
Exemple #34
0
def search():
    query = request.args('search')