Пример #1
0
def index():
	groups = request('groups')
	
	life = request('life_list')
	life.sort()
	
	#camps = request('camp_list')
	#camps.sort()
	
	stats = request('stats')
	
	return render_template('index.html', stats=stats, life=life, groups=groups)
Пример #2
0
def get_dimensions(index):
    """ Get all dimensions """

    # Build query for all types in index
    params = {
        'size': 0,
        'facets': {
            'types': {
                'terms': {
                    'field': '_type'
                }
            }
        }
    }

    # Make request
    response = request('search', index, None, params)

    # Map dimensions to list
    dimensions = map(lambda x: x['term'], response['facets']['types']['terms'])

    # Remove "observation" as this is the data itself (not a dimension)
    dimensions = filter(lambda x: x != 'observation', dimensions)

    return dimensions
Пример #3
0
def get_pdf(invoice):
    if current_user.is_authenticated:
        grandTotal = 0
        subTotal = 0
        customer_id = current_user.id
        if request.method == "POST":
            customer = Register.query.filter_by(id=customer_id).first()
            orders = CustomerOrder.query.filter_by(
                customer_id=customer_id,
                invoice=invoice).order_by(CustomerOrder.id.desc()).first()
            for _key, product in orders.orders.items():
                discount = (product['discount'] / 100) * float(
                    product['price'])
                subTotal += float(product['price']) * int(product['quantity'])
                subTotal -= discount
                tax = ("%.2f" % (.06 * float(subTotal)))
                grandTotal = float("%.2f" % (1.06 * subTotal))

            rendered = render_template('customer/pdf.html',
                                       invoice=invoice,
                                       tax=tax,
                                       grandTotal=grandTotal,
                                       customer=customer,
                                       orders=orders)
            pdf = pdfkit.from_string(rendered, False)
            response = make_response(pdf)
            response.headers['content-Type'] = 'application/pdf'
            response.headers[
                'content-Disposition'] = 'inline; filename=' + invoice + '.pdf'
            return response
    return request(url_for('orders'))
Пример #4
0
def upload():
    with open('capture.jpg', 'wb') as f:
        f.write(request.data)
    process_request = request('http://<ip-of-device>:5001/detect',
                              files={'image': open('capture.jpg', 'rb')})
    process_request.raise_for_status()

    return 'OK, saved file'
Пример #5
0
def search2(bearer_token, term, location):

    url_params = {
        'term': term.replace(' ', '+'),
        'location': location.replace(' ', '+'),
        'limit': 20
    }
    return request(API_HOST, SEARCH_PATH, bearer_token, url_params=url_params)
Пример #6
0
def sendTextMessage(sender, message):
    messageHead = {
        'url': 'https://graph.facebook.com/v2.6/me/messages',
        'qs': {
            'access_token': PAGE_TOKEN
        },
        'method': 'POST',
        'json': {
            'recipient': {
                'id': sender
            },
            'message': {
                'text': message
            }
        }
    }
    request(messageHead, errorHandler)
Пример #7
0
def index():
    """
    View root page function that returns index page and the various news sources
    """
    title = 'Home- Welcome News Highlights Website'
    # Getting the news sources
    news_sources = request('sources')
    return render_template('index.html', title=title, sources=news_sources)
Пример #8
0
def index():
    form = InputName()

    if request.method == 'POST':

        if request.form['submit'] == 'Повторить':
            return request('/index.html', form=form)

        if request.form['submit'] == 'Добавить имя':
            if form.name.data == '':
                return render_template("/index.html",
                                       form=form,
                                       error=form.name.data)
            elif Table.query.filter_by(name=form.name.data).first() is None:
                n = Table(name=form.name.data)
                db.session.add(n)
                db.session.commit()
                return render_template("/index.html",
                                       form=form,
                                       succuss_add=form.name.data)
            else:
                return render_template("/index.html",
                                       form=form,
                                       error_add_already=form.name.data)

        elif request.form['submit'] == 'Удалить имя':
            if form.name.data == '':
                return render_template("/index.html",
                                       form=form,
                                       error=form.name.data)
            elif Table.query.filter_by(name=form.name.data).first():
                Table.query.filter(Table.name == form.name.data).delete()
                db.session.commit()
                return render_template("/index.html",
                                       form=form,
                                       succuss_del=form.name.data)
            else:
                return render_template("/index.html",
                                       form=form,
                                       error_del='error')

        elif request.form['submit'] == 'Выбрать случайных победителей':
            id_list = []
            result = []
            for i in db.session.query(Table.name):
                id_list.append(i)

            if len(id_list) <= 3:
                for i in id_list:
                    result.append(i[-1])
            else:
                while len(result) < 3:
                    nm = random.choice(id_list)[-1]
                    if nm not in result:
                        result.append(nm)
            return render_template('/success.html', result=result)

    return render_template('/index.html', form=form)
def retry_request(request=None, num_tries=0, action='complete request', *args, **kwargs):
    max_retries = 5
    wait_time = 3
    if num_tries < 0:
        num_tries = 0

    try:
        if num_tries == 0:
            logger.exception('Failed to %; restarting communication module and trying again (try #1):' % action)
        elif num_tries < max_retries:
            logger.exception('Failed to %; restarting communication module and trying again in %d seconds (try #%d):'
                             % (action, wait_time, num_tries + 1))
            time.sleep(wait_time)
        num_tries += 1
        restart_comms_module()
        request(num_tries=num_tries, *args, **kwargs)
    except Exception as e:
        retry_request(request=request, num_tries=num_tries, action=action, *args, **kwargs)
Пример #10
0
def search(bearer_token, lat, lon, rad):

    url_params = {
        'latitude': lat,
        'longitude': lon,
        'limit': SEARCH_LIMIT,
        'radius': rad
    }
    return request(API_HOST, SEARCH_PATH, bearer_token, url_params=url_params)
Пример #11
0
def get_business(bearer_token, business_id):
    """Query the Business API by a business ID.
    Args:
        business_id (str): The ID of the business to query.
    Returns:
        dict: The JSON response from the request.
    """
    business_path = BUSINESS_PATH + business_id
    return request(API_HOST, business_path, bearer_token)
Пример #12
0
def scrape():

    # Run scrapped functions
    mars_info = mongo.db.mars_info
    mars_data = scrape_mars.scrape_mars_news()
    mars_data = scrape_mars.scrape_mars_image()
    mars_data = scrape_mars.scrape_mars_hemisphere()
    mars_info.update({}, mars_data, upsert=True)

    return request("/", code=302)
Пример #13
0
def get_business(business_id):
    """Query the Business API by a business ID.
    Args:
        business_id (str): The ID of the business to query.
    Returns:
        dict: The JSON response from the request.
    """
    business_path = BUSINESS_PATH + business_id

    return request(API_HOST, business_path)
Пример #14
0
def result():
	
	print "Got Post Info"

	user = request.form['user']
	location = request.form['location']
	languages = request.form['languages']
	comment = request.form['comment']

	return render_template('result.html', user = user, location = location, languages = languages, comment = comment)
	return request('/', )
Пример #15
0
def com_access_token():
    # 通过ticket 获取第三方接口调用凭据
    ticket = dao_wxapi.read_data("ticket")
    data = {
        "component_appid": appid,
        "component_appsecret": appsecret,
        "component_verify_ticket": ticket
    }
    url_com_access_token = config.URL_COM_ACCESS_TOKEN
    dict_data = request("POST", url_com_access_token, data)
    com_access_token = dict_data["component_access_token"]
    dao_wxapi.save("com_access_token", com_access_token)
Пример #16
0
def get_movie(movie_id):
  
    movie = request('GET', '/3/movie/{}?'.format(movie_id))
    movie = json.loads(movie)

    #add new movie to database
    try:
      print('The movie is added to the database')
    except BaseException as e:
      print('Could not insert data into the database. Response from API: ' + str(movie) + '    ' + str(e))

    print('Movie is in the database')
    return "movie in database"
Пример #17
0
def pre_auth_code():
    # 通过com_access_token获取预授权码
    com_access_token = dao_wxapi.read_data("com_access_token")
    data = {"component_appid": appid}
    url_pre_auth_code = config.URL_PRE_AUTH_CODE.format(com_access_token)
    dict_data = request("POST", url_pre_auth_code, data)
    pre_auth_code = dict_data.get("pre_auth_code") or ''
    if not pre_auth_code:
        log_error(
            "pre_auth_code get failed: appid: {}, com_access_token: {}".format(
                appid, com_access_token))
    dao_wxapi.save("pre_auth_code", pre_auth_code)
    return pre_auth_code
Пример #18
0
def add_random_player():
    form = PlayerForm()
    helloJson = request()
    player = Player()
    player.name = helloJson['name']
    player.birthdate = helloJson['birth_data']
    player.height = helloJson['height']
    player.weight = helloJson['weight'] 
    becauseDebugging = random.randint(1,Team.query.count())
    player.team_id = becauseDebugging
    db.session.add(player)
    db.session.commit()
    flash("Random player " + player.name + " was born on " + player.birthdate )
    return redirect(url_for("index"))
Пример #19
0
def search(lat , lon):
	"""Query the Search API by a search term and location.
		"""
	url_params = {
	#'term': term.replace(' ', '+'),
	#'location': location.replace(' ', '+'),
	'll': lat + "," + lon,
	#'category':"american", 
	#'name' : "villabate alba",
	'limit': SEARCH_LIMIT
	
	}
	print (url_params)
	return request(API_HOST, SEARCH_PATH, url_params=url_params)
Пример #20
0
 def response(query):
     content = request(query)
     root = ET.fromstring(content)
     error = root.get('error')
     success = root.get('success')
     numpods = root.get('numpods')
     print(numpods, success)
     answer= ''
     if success and int(numpods) > 0 :
         for plaintext in root.iter('plaintext'):
             if isinstance(plaintext.text, str) :
                 answer = answer + plaintext.text
         return answer
     elif error:
         return "Server is busy. Please try again."
def search(bearer_token, term, location):
    """Query the Search API by a search term and location.
    Args:
        term (str): The search term passed to the API.
        location (str): The search location passed to the API.
    Returns:
        dict: The JSON response from the request.
    """

    url_params = {
        'term': term.replace(' ', '+'),
        'location': location.replace(' ', '+'),
        'limit': SEARCH_LIMIT
    }
    return request(API_HOST, SEARCH_PATH, bearer_token, url_params=url_params)
Пример #22
0
def reset_password(token):
    if current_user.is_authenticated:
        return request(url_for('index'))

    user = User.verify_reset_password_token(token)
    if not user:
        return redirect(url_for('index'))

    form = ResetPasswordForm()
    if form.validate_on_submit():
        user.set_password(form.password.data)
        db.session.commit()
        flash('Your password has been reset.')
        return redirect(url_for('login'))
    return render_template('reset_password.html', form=form)
Пример #23
0
def search():
    if request.method == "GET":
        return request(url_for("index"))
    else:
        keyword = request.form.get("keyword")

        cursor = mysql.connection.cursor()
        sorgu = "Select *From articles where title like '%" + keyword + "%' "
        result = cursor.execute(sorgu)

        if result > 0:
            articles = cursor.fetchall()
            return render_template("articles.html", articles=articles)
        else:
            flash("Aranan Kriterlere Uygun Makale Bulunamadı", "warning")
            return redirect(url_for("articles"))
Пример #24
0
def upload_file():
    if 'user' not in session:
        return request(url_for('index'))
    file=request.files['avatar']
    if file and allowed_file(file.filename):
        # print(os.listdir(UPLOAD_FOLDER))
        files_in_directory = [f for f in os.listdir(UPLOAD_FOLDER) if f.rsplit('.', 1)[0] == session['user']['login']]
        # print(files_in_directory)
        for file_previous in files_in_directory:
            os.remove(os.path.join(UPLOAD_FOLDER, file_previous))
        filename = session['user']['login'] + '.' + file.filename.rsplit('.', 1)[1]
        file.save(os.path.join(UPLOAD_FOLDER, filename))
        flash('Successfully!')
    # print('!!!')
    response = make_response(redirect(url_for('get_user', username=session['user']['login'])))
    return response
Пример #25
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request(url_for('login'))
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('login.html', title='Sign In', form=form)
Пример #26
0
def get_items_state(list_item_global_id):
    message_request = {
        'list_item_global_id': list_item_global_id,
        'reply_to': "dbreader.response.api.api_get_item_state"
    }

    # request to api_get_things of Registry
    queue_response = Queue(
        name='dbreader.response.api.api_get_item_state',
        exchange=exchange,
        routing_key='dbreader.response.api.api_get_item_state')
    request_routing_key = 'dbreader.request.api_get_item_state'
    message_response = request(rabbitmq_connection, message_request, exchange,
                               request_routing_key, queue_response)
    # message_response = {"items": [{'item_global_id': "", 'item_state': "", 'last_changed': ""}]}
    return message_response
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('admin'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That is an invalid or expired token', 'warning')
        return redirect(url_for('reset_request'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash('your password has been updated. You are now able to login now',
              'success')
        return request(url_for('login'))
    return render_template('reset_token.html', form=form)
Пример #28
0
def refresh_info():
    appid = config.WXAPPID
    user_info_list = dao_wxapi.read_info()
    update_list = []
    for user_info in user_info_list:
        # 循环获取授权方基本信息
        com_access_token = dao_wxapi.read_data("com_access_token")
        url_getinfo = config.URL_GETINFO.format(com_access_token)
        authorizer_appid = user_info["appid"]
        data_info = {
            "component_appid": appid,
            "authorizer_appid": authorizer_appid
        }
        info_dict_data = request("POST", url_getinfo, data_info)
        rsp_dict = do_refresh_info(info_dict_data, user_info)
        update_list.append({user_info["nick_name"]: rsp_dict})
    return update_list
Пример #29
0
    def resolve_conflicts(self): #共识算法
        neighbors = self.nodes
        current_chain = self.chain
        current_length = len(self.chain)
        for node in neighbors:
            response = request(f'http://{node}/chain')
            if response.status_code == 200:
                let jsonData = response.json()
                length = jsonData["length"]
                new_chain = jsonData["chain"]

                if length > current_length and self.valid_chain(new_chain):
                    current_length = length
                    current_chain = new_chain
                    return True
                else:
                    return False
Пример #30
0
def supCalendarPage():
    username = ''
    actList = []
    friendList = []
    supList = []
    if 'username' not in session:
            return request(url_for('index'))
    username = session['username']
    friends = database.findCon(session['uid']);
    for friend in friends:
        friendList.append({'id':friend[0], 'name':friend[1], 'isChecked':0, "weight":1.0})

    if request.method == 'POST':   
        # print("request",request.getWriter().print(json.toJSONString()))     
        data = request.get_json()
        print("data",data)
        for f in data["supList"]:
            fid = f["id"]
            fweight = f["weight"]
            fname = database.getUsernameByUid(fid)[0][0]
            supList.append({"id":int(fid), "name": fname, "weight":float(fweight)})
    else:
        supList = friendList[:]
    print("supList",supList)
    for friend in friendList:
        for sup in supList:
            if friend['id'] == sup['id']:
                friend['isChecked']=1
                friend["weight"]=sup["weight"]
    supList.append({'id':session['uid'], 'name':session['username'], "weight":1.0})
    for friend in supList:
        activities = database.findActivitiesByUser(friend['id'])
        fweight = friend["weight"]
        for activity in activities:
            act={}
            act["title"] = activity[2]
            act["start"] = activity[3]
            act["end"] = activity[4]
            act["willingness"] = activity[5]
            act["category"] = activity[6]
            act["description"] = activity[7]
            act["weight"] = fweight
            actList.append(act)
    print("friendlist",friendList)
    return render_template("supCalendarPage.html", uname=username, friendList=friendList, actList=actList)
Пример #31
0
def get_thing_info_by_global_id(thing_global_id):

    print("API get things by thing_global_id")
    message_request = {
        'reply_to': 'registry.response.api.api_get_thing_by_global_id',
        'thing_global_id': thing_global_id
    }

    # request to api_get_things of Registry
    queue_response = Queue(
        name='registry.response.api.api_get_thing_by_global_id',
        exchange=exchange,
        routing_key='registry.response.api.api_get_thing_by_global_id')
    request_routing_key = 'registry.request.api_get_thing_by_global_id'
    message_response = request(rabbitmq_connection, message_request, exchange,
                               request_routing_key, queue_response)

    return message_response
Пример #32
0
def postQuestion(id, toPost):
    questions = Question.query.order_by('id').all()
    question = Question.query.get(id)
    tree = ET.fromstring(question.xml)
    headers = {'content-type': 'application/json'}
    if toPost == 'question':
        json = question.json()
    elif toPost == 'answer':
        json = question.json(postQuestion=False, postAnswer=True)
    else:
        json = question.json(postAnswer=True)
    form = PostForm(url="http://echoing.herokuapp.com/", payload=json)
    if form.validate_on_submit():
        request = requestMethod(form.method.data)
        response = request(form.url.data, data=form.payload.data, headers=headers)
        return render_template('postQuestion.html', questions=questions, id=id, form=form, response=response)
    else:
        return render_template('postQuestion.html', questions=questions, id=id, form=form)
Пример #33
0
def autocomplete():
    if request.method == 'POST':
        search_term = request.form["input"]
        print("POST request called")
        print(search_term)
        payload = {
            "autocomplete": {
                "text": str(search_term),
                "completion": {
                    "field": "title_suggest"
                }
            }
        }
        payload = json.dumps(payload)
        url = "http://localhost:9200/autocomplete/_suggest"
        response = request("GET", url, data=payload, headers=headers)
        response_dict_data = json.loads(str(response.text))
        return json.dumps(response_dict_data)
Пример #34
0
def votings(voting_id):
    # Получение информации
    if request.method == 'GET':
        pass

    # Создание голосования
    if request.method == 'POST':
        return creat_voting()

    # Изменение информации
    if request.method == 'PUT':
        pass

    # Удаление запроса
    if request.method == 'DELETE':
        pass

    return request('')
Пример #35
0
def answers(voting_id, ansver_id):
    # Получение информации ответа
    if request.method == 'GET':
        pass

    # Создание ответа
    if request.method == 'POST':
        pass

    # Изменение информации ответа
    if request.method == 'PUT':
        pass

    # Удаление ответа
    if request.method == 'DELETE':
        pass

    return request('')
Пример #36
0
def calc():
    # form = ObjectDetectionForm()
    form_od = ObjectDetectionForm()
    data_cam = 'SSD MOBILE NET'
    if data_cam == 'SSD MOBILE NET':
        return Response(get_frame_ssd(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    elif data_cam == 'DLIB Face Recognition':
        return Response(get_frame_dlib(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    elif data_cam == 'ResNet10 Face Recognition':
        return Response(get_frame_res10(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        return Response(get_frame_norm(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

    return request(url_for('camera.calc_ord'))
Пример #37
0
def authorizer_access_token(auth_code, set_map=True):
    # 通过com_access_token获取公众号/小程序接口调用凭据/令牌
    # 以及刷新凭据/刷新令牌
    rsp_dict = {"sign": 0, "msg": ''}
    com_access_token = dao_wxapi.read_data("com_access_token")
    auth_code = auth_code  # dao_wxapi.read_data("auth_code")
    data = {"component_appid": appid, "authorization_code": auth_code}
    url_authorizer_access_token = config.URL_AUTHORIZER_ACCESS_TOKEN.format(
        com_access_token)
    dict_data = request("POST", url_authorizer_access_token, data)
    send_log("AuthorizationAccountInfo:" + str(dict_data))
    auth_info_all = ''
    if "authorization_info" in dict_data:
        # 授权信息
        rsp_dict = do_authorizer_access_token(dict_data,
                                              auth_code,
                                              set_map=set_map)
    else:
        rsp_dict["msg"] = "微信服务器故障: authorizer_info not in response"

    return rsp_dict
Пример #38
0
def edit_cat(category_name):
    cat_edit = session.query(Category).filter_by(name=category_name).one()
    category = session.query(Category).filter_by(name=category_name).one()
    """See if the logged in user is the owner of item"""
    creator = getUserInfo(cat_edit.user_id)
    user = getUserInfo(login_session['user_id'])
    # If logged in user != item owner redirect them
    if creator.id != login_session['user_id']:
        print ("You cannot edit this Category. This Category belongs to %s" % creator.name)
        return redirect(url_for('Itemcatalog'))
    # Post Method Form
    if request.method == 'POST':
        if request.form['name']:
            cat_edit.name = request.form['name']
            session.add(cat_edit)
            session.commit()
            print("Category item have been sucesfuly edited")
            return request(url_for('Itemcatalog'))
    else:
        return render_template('edit_category.html', categories=cat_edit,
                                   category=category)
Пример #39
0
def simple_request_url(url, data = None, timeout = None, return_response_object = False, 
                       head = False, cookiejar = None, useragent = None, disable_proxy = None,
                       internal_request = False):
    # urllib2 won't escape spaces and without doing this here some requests will fail
    url     = url.replace(' ', '%20')
    host    = None
    urlp    = None
    
    if internal_request == 'detect':
        urlp = urlp or urlparse.urlparse(url)
        internal_request = urlp.netloc == config['DEFAULT_SERVER_NAME']
    
    if internal_request:
        if disable_proxy is None:
            disable_proxy = True
        
        urlp = urlp or urlparse.urlparse(url)
        host = urlp.netloc
        url  = "http://%(host)s%(url)s" % dict(host = config['INTERNAL_SERVER_NAME'], url = urlp.path + ('?' + urlp.query if urlp.query else ''))
    
    request = HeadRequest if head else urllib2.Request 
    request = request(url)
    request.add_header('User-Agent', useragent or UPCOMING_USERAGENT)
    
    if host:
        request.add_header('Host', host)
    
    handlers = []
    if cookiejar:
        handlers.append(urllib2.HTTPCookieProcessor(cookiejar))
    if disable_proxy:
        handlers.append(urllib2.ProxyHandler({}))
    
    opener = urllib2.build_opener(*handlers)
    
    timeout = timeout or 30
    response = opener.open(request, data, timeout)
    
    return response if return_response_object else response.read()
Пример #40
0
def edit(id):
    if('user' in session and session['user'] == params['admin_user']):
        if request.method=="POST":
            title = request.form.get('title')
            content = request.form.get('content')
            slug = request.form.get('slug')
            img_file = request.form.get('img_file')
            date = datetime.now()
            if id=='0':
                post = Post(title=title, content=content, date=date, slug=slug, file_image=img_file)
                db.session.add(post)
                db.session.commit()
            else:
                post= Post.query.filter_by(id=id).first()
                post.title = title
                post.content = content
                post.date = date
                post.slug = slug
                post.file_image = img_file
                db.commit()
                return request('/edit/'+id)
        post = Post.query.filter_by(id=id).first()
        return render_template('edit.html', params=params, post=post)
Пример #41
0
def get_business(business_id):
	"""Query the Business API by a business ID.

	"""
	business_path = BUSINESS_PATH + business_id
	return request(API_HOST, business_path)
Пример #42
0
def memory(life_id):
	memories = request('memory', value=int(life_id))
	
	return render_template('memory.html', life_id=life_id, memories=memories)
Пример #43
0
def life(life_id):
	life = request('life', value=int(life_id))
	knows = life['know'].values()
	
	return render_template('life.html', life=life, knows=knows)
Пример #44
0
def camp(camp_id):
	camp = request('camp', value=int(camp_id))
	
	return render_template('camp.html', camp=camp)
Пример #45
0
def group(group_id):
	groups = request('groups')
	group = groups[group_id]
	
	return render_template('group.html', group_id=group_id, group=group)