コード例 #1
0
ファイル: cron.py プロジェクト: kadarivan/osm-gimmisn
def main() -> None:
    """Commandline interface to this module."""

    util.set_locale()

    workdir = util.Config.get_workdir()
    relations = areas.Relations(workdir)
    logpath = os.path.join(workdir, "cron.log")
    logging.basicConfig(filename=logpath,
                        level=logging.INFO,
                        format='%(asctime)s %(levelname)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    handler = logging.StreamHandler()
    logging.getLogger().addHandler(handler)

    start = time.time()
    relations.activate_all(util.Config.get_cron_update_inactive())
    try:
        our_main(relations)
    # pylint: disable=broad-except
    except Exception:
        logging.error("main: unhandled exception: %s", traceback.format_exc())
    delta = time.time() - start
    logging.info("main: finished in %s",
                 str(datetime.timedelta(seconds=delta)))
    logging.getLogger().removeHandler(handler)
    logging.shutdown()
コード例 #2
0
def our_application(
        environ: Dict[str, Any],
        start_response: 'StartResponse'
) -> Iterable[bytes]:
    """Dispatches the request based on its URI."""
    util.set_locale()

    language = util.setup_localization(environ)

    relations = areas.Relations(config.Config.get_workdir())

    request_uri = webframe.get_request_uri(environ, relations)
    _, _, ext = request_uri.partition('.')

    if ext in ("txt", "chkl"):
        return our_application_txt(environ, start_response, relations, request_uri)

    prefix = config.Config.get_uri_prefix()
    found = request_uri == "/" or request_uri.startswith(prefix)
    if not found:
        doc = webframe.handle_404()
        return webframe.send_response(environ,
                                      start_response,
                                      webframe.ResponseProperties("text/html", "404 Not Found"),
                                      doc.getvalue().encode("utf-8"),
                                      [])

    if request_uri.startswith(prefix + "/static/") or request_uri.endswith("favicon.ico"):
        output, content_type, extra_headers = webframe.handle_static(request_uri)
        return webframe.send_response(environ,
                                      start_response,
                                      webframe.ResponseProperties(content_type, "200 OK"),
                                      output,
                                      extra_headers)

    if ext == "json":
        return wsgi_json.our_application_json(environ, start_response, relations, request_uri)

    doc = yattag.doc.Doc()
    util.write_html_header(doc)
    with doc.tag("html", lang=language):
        write_html_head(doc, get_html_title(request_uri))

        with doc.tag("body"):
            no_such_relation = webframe.check_existing_relation(relations, request_uri)
            handler = get_handler(request_uri)
            if no_such_relation.getvalue():
                doc.asis(no_such_relation.getvalue())
            elif handler:
                doc.asis(handler(relations, request_uri).getvalue())
            elif request_uri.startswith(prefix + "/webhooks/github"):
                doc.asis(handle_github_webhook(environ).getvalue())
            else:
                doc.asis(handle_main(request_uri, relations).getvalue())

    return webframe.send_response(environ,
                                  start_response,
                                  webframe.ResponseProperties("text/html", "200 OK"),
                                  doc.getvalue().encode("utf-8"),
                                  [])
コード例 #3
0
ファイル: cron.py プロジェクト: zsolt-beringer/osm-gimmisn
def main() -> None:
    """Commandline interface to this module."""

    config = configparser.ConfigParser()
    config_path = util.get_abspath("wsgi.ini")
    config.read(config_path)
    util.set_locale(config)

    workdir = util.get_workdir(config)
    relations = areas.Relations(workdir)
    logpath = os.path.join(workdir, "cron.log")
    logging.basicConfig(filename=logpath,
                        level=logging.INFO,
                        format='%(asctime)s %(levelname)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    handler = logging.StreamHandler()
    logging.getLogger().addHandler(handler)

    start = time.time()
    # Query inactive relations once a month.
    relations.activate_all(time.localtime(start).tm_mday == 1)
    try:
        our_main(relations, config)
    # pylint: disable=broad-except
    except Exception:
        logging.error("main: unhandled exception: %s", traceback.format_exc())
    delta = time.time() - start
    logging.info("main: finished in %s", str(datetime.timedelta(seconds=delta)))
    logging.getLogger().removeHandler(handler)
    logging.shutdown()
コード例 #4
0
ファイル: cron.py プロジェクト: meskobalazs/osm-gimmisn
def main() -> None:
    """Commandline interface to this module."""

    util.set_locale()

    workdir = config.Config.get_workdir()
    relations = areas.Relations(workdir)
    logpath = os.path.join(workdir, "cron.log")
    logging.basicConfig(filename=logpath,
                        level=logging.INFO,
                        format='%(message)s')
    handler = logging.StreamHandler()
    logging.getLogger().addHandler(handler)

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--refcounty",
        type=str,
        help="limit the list of relations to a given refcounty")
    parser.add_argument(
        "--refsettlement",
        type=str,
        help="limit the list of relations to a given refsettlement")
    parser.add_argument('--no-update',
                        dest='update',
                        action='store_false',
                        help="don't update existing state of relations")
    parser.add_argument("--mode",
                        choices=["all", "stats", "relations"],
                        help="only perform the given sub-task or all of them")
    parser.add_argument(
        "--no-overpass",
        dest="overpass",
        action="store_false",
        help="when updating stats, don't perform any overpass update")
    parser.set_defaults(update=True, overpass=True, mode="relations")
    args = parser.parse_args()

    start = time.time()
    # Query inactive relations once a month.
    first_day_of_month = time.localtime(start).tm_mday == 1
    relations.activate_all(config.Config.get_cron_update_inactive()
                           or first_day_of_month)
    relations.limit_to_refcounty(args.refcounty)
    relations.limit_to_refsettlement(args.refsettlement)
    try:
        our_main(relations, args.mode, args.update, args.overpass)
    # pylint: disable=broad-except
    except Exception:
        error("main: unhandled exception: %s", traceback.format_exc())
    delta = time.time() - start
    info("main: finished in %s", str(datetime.timedelta(seconds=delta)))
    logging.getLogger().removeHandler(handler)
    logging.shutdown()
コード例 #5
0
ファイル: auth.py プロジェクト: NamPNQ/gae-init-babel
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  if login.login_user(flask_user_db):
    flask.flash(__('Hello %(name)s, welcome to %(brand)s!!!',
        name=user_db.name, brand=config.CONFIG_DB.brand_name,
      ), category='success')
    response = flask.redirect(util.get_next_url())
    util.set_locale(user_db.locale, response)
    return response
  else:
    flask.flash(__('Sorry, but you could not sign in.'), category='danger')
    return flask.redirect(flask.url_for('signin'))
コード例 #6
0
def signin_user_db(user_db):
    if not user_db:
        return flask.redirect(flask.url_for('signin'))
    flask_user_db = FlaskUser(user_db)
    if login.login_user(flask_user_db):
        flask.flash(__(
            'Hello %(name)s, welcome to %(brand)s!!!',
            name=user_db.name,
            brand=config.CONFIG_DB.brand_name,
        ),
                    category='success')
        response = flask.redirect(util.get_next_url())
        util.set_locale(user_db.locale, response)
        return response
    else:
        flask.flash(__('Sorry, but you could not sign in.'), category='danger')
        return flask.redirect(flask.url_for('signin'))
コード例 #7
0
ファイル: auth.py プロジェクト: Xxpansion/gae-init-babel
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
      'next': flask.url_for('welcome'),
      'remember': False,
    })
  if login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    response = flask.redirect(auth_params['next'])
    util.set_locale(user_db.locale, response)
    flask.flash(__(
        'Hello %(name)s, welcome to %(brand)s.',
        name=user_db.name, brand=config.CONFIG_DB.brand_name,
      ), category='success')
    return response
  flask.flash(__('Sorry, but you could not sign in.'), category='danger')
  return flask.redirect(flask.url_for('signin'))
コード例 #8
0
def our_application(environ: Dict[str, Any],
                    start_response: 'StartResponse') -> Iterable[bytes]:
    """Dispatches the request based on its URI."""
    util.set_locale()

    language = util.setup_localization(environ)

    relations = areas.Relations(util.Config.get_workdir())

    request_uri = get_request_uri(environ, relations)
    _, _, ext = request_uri.partition('.')

    if ext in ("txt", "chkl"):
        return our_application_txt(start_response, relations, request_uri)

    prefix = util.Config.get_uri_prefix()
    if request_uri.startswith(prefix + "/static/"):
        output, content_type = webframe.handle_static(request_uri)
        return webframe.send_response(start_response, content_type, "200 OK",
                                      output, [])

    doc = yattag.doc.Doc()
    util.write_html_header(doc)
    with doc.tag("html", lang=language):
        write_html_head(doc, get_html_title(request_uri))

        with doc.tag("body"):
            no_such_relation = check_existing_relation(relations, request_uri)
            handler = get_handler(request_uri)
            if no_such_relation.getvalue():
                doc.asis(no_such_relation.getvalue())
            elif handler:
                doc.asis(handler(relations, request_uri).getvalue())
            elif request_uri.startswith(prefix + "/webhooks/github"):
                doc.asis(handle_github_webhook(environ).getvalue())
            else:
                doc.asis(handle_main(request_uri, relations).getvalue())

    return webframe.send_response(start_response, "text/html", "200 OK",
                                  doc.getvalue(), [])
コード例 #9
0
ファイル: auth.py プロジェクト: lipis/crypto-pocket
def signin_user_db(user_db):
    if not user_db:
        return flask.redirect(flask.url_for('signin'))
    flask_user_db = FlaskUser(user_db)
    auth_params = flask.session.get('auth-params', {
        'next': flask.url_for('welcome'),
        'remember': False,
    })
    flask.session.pop('auth-params', None)
    if flask_login.login_user(flask_user_db, remember=auth_params['remember']):
        user_db.put_async()
        return util.set_locale(
            user_db.locale,
            flask.redirect(util.get_next_url(auth_params['next'])),
        )
    flask.flash(__('Sorry, but you could not sign in.'), category='danger')
    return flask.redirect(flask.url_for('signin'))
コード例 #10
0
ファイル: auth.py プロジェクト: gae-init/gae-init-babel
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if flask_login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    return util.set_locale(
      user_db.locale,
      flask.redirect(util.get_next_url(auth_params['next'])),
    )
  flask.flash(__('Sorry, but you could not sign in.'), category='danger')
  return flask.redirect(flask.url_for('signin'))
コード例 #11
0
def set_locale(locale):
    response = flask.redirect(util.get_next_url())
    util.set_locale(locale, response)
    return response
コード例 #12
0
ファイル: auth.py プロジェクト: NamPNQ/gae-init-babel
def set_locale(locale):
  response = flask.redirect(util.get_next_url())
  util.set_locale(locale, response)
  return response
コード例 #13
0
ファイル: auth.py プロジェクト: mdxs/gae-init-babel
def request_finished(sender, response, **extra):
  if util.param('hl'):
    util.set_locale(check_locale(util.param('hl')), response)
コード例 #14
0
ファイル: auth.py プロジェクト: lipis/crypto-pocket
def set_locale(locale):
    return util.set_locale(locale, flask.redirect(util.get_next_url()))
コード例 #15
0
ファイル: auth.py プロジェクト: lipis/crypto-pocket
def request_finished(sender, response, **extra):
    util.set_locale(util.param('hl'), response)
コード例 #16
0
ファイル: auth.py プロジェクト: gae-init/gae-init-babel
def set_locale(locale):
  return util.set_locale(locale, flask.redirect(util.get_next_url()))