def spectrum_download_txt(spectrum_id, download_filename):
  spectrum = Spectrum.query.get(spectrum_id)
  with gzip.open(spectrum.gz_file_path(), 'r') as f:
    data = f.read()
  mimetype = 'text/plain'
  rv = app.response_class(data, mimetype=mimetype, direct_passthrough=True)
  return rv
Example #2
0
def new_game():
    global user_data

    req_data = request.get_json()
    logging.error(req_data)
    id = req_data['id']

    user = User.query.filter_by(sber_id=id).first()
    res = {}
    if user is None:
        db.session.add(User(id, 0, -1))
        db.session.commit()
        res = {'level': 0, 'diff': -1}
    else:
        res = {'level': user.level, 'diff': user.difficulty}
        user_data[id] = {
            'word_list':
            list(
                map(
                    lambda word: (word.rus, word.eng),
                    Word.query.filter_by(level=res['level'],
                                         difficulty=res['diff']).limit(5))),
            'cur_word':
            0,
            'testing_phase':
            False,
        }

    logging.error(user_data)

    response = app.response_class(response=json.dumps(res),
                                  status=200,
                                  mimetype='application/json')
    return response
Example #3
0
def __make_response(
        code: int,
        payload: dict,
        mimetype: str = 'application/json') -> "Flask.response_class":
    """Generate Flask.response_class from response code and dictionary."""
    # Paranoia check
    assert (isinstance(payload, dict))
    assert (isinstance(code, int))

    try:
        #
        # Common api element for JSON responses
        #
        payload['api'] = {
            'version': app.apiversion,
            't_cpu': time.process_time() - g.t_cpu_start,
            't_real': time.perf_counter() - g.t_real_start
        }
        # NOTE: PLEASE remove 'indent' and 'sort_keys' when developing is done!!!
        # 'default=str' is useful setting to handle obscure data, leave it.
        # (for example; "datetime.timedelta(31) is not JSON serializable")
        # https://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify
        t = time.perf_counter()
        #payload = json.dumps(payload, indent=4, sort_keys=True, default=str)
        #app.logger.debug("REMOVE SORT! json.dumps(): {:.1f}ms".format((time.perf_counter() - t) * 1000))
        payload = json.dumps(payload, default=str)

        response = app.response_class(response=payload,
                                      status=code,
                                      mimetype=mimetype)
        # Send list of allowed methods for this endpoint in the header
        allow = [
            method for method in request.url_rule.methods
            if method not in ('HEAD', 'OPTIONS')
        ]
        response.headers['Allow'] = ", ".join(allow)
        response.headers['Content-Type'] = mimetype
        return response
    except Exception as e:
        # VERY IMPORTANT! Do NOT re-raise the exception!
        app.logger.exception("api.__make_response(): Internal error!")
        # We will try to offer dict instead of Flask.Response...
        #return ("api.__make_response() Internal Error!", 500)
        return app.response_class(
            response=f"api.__make_response() Internal Error: {str(e)}",
            status=500)
Example #4
0
def response(data, sta):
    if game_end:
        global board, turn
        turn = 0
        board = game_board()
    response = app.response_class(response=json.dumps(data),
                                  status=sta,
                                  mimetype='application/json')
    return response
def analogue_download_all_txt(analogue_id):
  spectra = Analogue.query.get(analogue_id).spectra
  stream = io.BytesIO()
  with tarfile.open(mode='w:gz', fileobj=stream) as tar:
    for spectrum in spectra:
      with gzip.open(spectrum.gz_file_path(), 'r') as f:
        buff = f.read()
        tarinfo = tarfile.TarInfo(name=str(spectrum.temperature)+'K.txt')
        tarinfo.size = len(buff)
        tar.addfile(tarinfo=tarinfo, fileobj=io.BytesIO(buff))
  data = stream.getvalue()
  mimetype = 'application/x-tar'
  rv = app.response_class(data, mimetype=mimetype, direct_passthrough=True)
  return rv
Example #6
0
def set_diff():
    global user_data

    req_data = request.get_json()
    logging.error(req_data)
    id = req_data['id']
    diff = req_data['diff']

    user = User.query.filter_by(sber_id=id).first()
    user.difficulty = diff
    user.level = 0
    db.session.commit()

    res = {}

    response = app.response_class(response=json.dumps(res),
                                  status=200,
                                  mimetype='application/json')
    return response
Example #7
0
# -*- coding: utf-8 -*-
Example #8
0
# -*- coding: utf-8 -*-
Example #9
0
# -*- coding: utf-8 -*-
Example #10
0
def api_doc():
    """JSON API Documentation.
    Generates API document from the available endpoints. This functionality
    relies on PEP 257 (https://www.python.org/dev/peps/pep-0257/) convention
    for docstrings and Flask micro framework route ('rule') mapping to
    generate basic information listing on all the available REST API functions.
    This call takes no arguments.
    
    GET /sys/api
    
    List of API endpoints is returned in JSON.
    
    GET /api.html
    
    The README.md from /api is prefixed to HTML content. List of API endpoints
    is included as a table."""
    def htmldoc(docstring):
        """Some HTML formatting for docstrings."""
        result = None
        if docstring:
            docstring = docstring.replace('<', '&lt;').replace('>', '&gt;')
            result = "<br/>".join(docstring.split('\n')) + "<br/>"
        return result

    try:
        log_request(request)
        eplist = []
        for rule in app.url_map.iter_rules():
            if rule.endpoint != 'static':
                allowed = [
                    method for method in rule.methods
                    if method not in ('HEAD', 'OPTIONS')
                ]
                methods = ','.join(allowed)

                eplist.append({
                    'service': rule.endpoint,
                    'methods': methods,
                    'endpoint': str(rule),
                    'doc': app.view_functions[rule.endpoint].__doc__
                })

        #
        # Sort eplist based on 'endpoint'
        #
        eplist = sorted(eplist, key=lambda k: k['endpoint'])

        if 'api.html' in request.url_rule.rule:
            try:
                from ext.markdown2 import markdown
                with open('api/README.md') as f:
                    readme = markdown(f.read(), extras=["tables"])
            except:
                app.logger.exception("Unable to process 'api/README.md'")
                readme = ''
            html = "<!DOCTYPE html><html><head><title>API Listing</title>"
            html += "<link rel='stylesheet' href='/css/api.css'>"
            # substitute for favicon
            html += "<link rel='icon' href='data:;base64,iVBORw0KGgo='>"
            html += "</head><body>"
            html += readme
            html += "<h2>List of Flask routes and Endpoints</h2>"
            html += "<table class='endpointTable'><tr><th>Service</th><th>Methods</th><th>Endpoint</th><th>Documentation</th></tr>"
            for row in eplist:
                html += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>" \
                        .format(
                            row['service'],
                            row['methods'],
                            row['endpoint'].replace('<', '&lt;').replace('>', '&gt;'),
                            htmldoc(row['doc'])
                        )
            html += "</table></body></html>"
            # Create Request object
            response = app.response_class(response=html,
                                          status=200,
                                          mimetype='text/html')
            return response
        else:
            return api.response((200, {'endpoints': eplist}))
    except Exception as e:
        return api.exception_response(e)
Example #11
0
def get_file(category_id):
        """k = db.Key.from_path('MediaKit', category_id)""" 
        mediakit = Mediakit.get_by_key_name(category_id)
        return app.response_class(mediakit.mediaurl,mimetype=mediakit.content_type,direct_passthrough=False)
Example #12
0
def get_img(app_id):
        """k = db.Key.from_path('MediaKit', category_id)""" 
        applist = AdNetwork.get_by_id(app_id)
        return app.response_class(applist.app_url,mimetype=applist.content_type,direct_passthrough=False)           
Example #13
0
# -*- coding: utf-8 -*-
Example #14
0
def next_word():
    global user_data

    req_data = request.get_json()
    logging.error(req_data)
    id = req_data['id']
    wa = req_data['wa']

    res = {}

    logging.error(user_data)

    if user_data[id]['testing_phase']:
        if wa == 0 and user_data[id]['cur_word'] == len(
                user_data[id]['word_list']):
            res = {'word_rus': '', 'word_eng': '', 'end': True}
            user = User.query.filter_by(sber_id=id).first()
            user.level += 1
            db.session.commit()
        elif user_data[id]['cur_word'] == -1:
            res = {'word_rus': '', 'word_eng': '', 'end': True}
            user_data[id]['cur_word'] += 1
        else:
            if wa == 1:
                logging.error("штука")
                user_data[id]['cur_word'] -= 1
                idx = user_data[id]['cur_word']
                wa_word = user_data[id]['word_list'].pop(idx)
                user_data[id]['word_list'].append(wa_word)
                cur_word = user_data[id]['word_list'][idx]
                res = {
                    'word_rus': cur_word[0],
                    'word_eng': cur_word[1],
                    'end': False
                }
                user_data[id]['cur_word'] += 1
            else:
                idx = user_data[id]['cur_word']
                cur_word = user_data[id]['word_list'][idx]
                res = {
                    'word_rus': cur_word[0],
                    'word_eng': cur_word[1],
                    'end': False
                }
                user_data[id]['cur_word'] += 1
    else:
        idx = user_data[id]['cur_word']
        cur_word = user_data[id]['word_list'][idx]
        res = {'word_rus': cur_word[0], 'word_eng': cur_word[1], 'end': False}
        user_data[id]['cur_word'] += 1
        if user_data[id]['cur_word'] == len(user_data[id]['word_list']):
            user_data[id]['cur_word'] = -1
            user_data[id]['testing_phase'] = True
            random.shuffle(user_data[id]['word_list'])

    logging.error(user_data)

    response = app.response_class(response=json.dumps(res),
                                  status=200,
                                  mimetype='application/json')
    return response