def main():
    log = logging.getLogger()
    log.setLevel(logging.INFO)
    ch_format = ColoredFormatter(
        "%(asctime)s - %(threadName)s - %(name)s - %(log_color)s %(levelname)s - %(reset)s %(purple)s %(message)s",
        datefmt=None,
        reset=True,
        log_colors={
            "DEBUG": "cyan",
            "INFO": "green",
            "WARNING": "yellow",
            "ERROR": "red",
            "CRITICAL": "red,bg_white",
        },
        secondary_log_colors={},
        style="%")
    ch = logging.StreamHandler(sys.stdout)
    ch.setFormatter(ch_format)
    log.addHandler(ch)

    if not os.path.exists(LOG_FOLDER):
        try:
            log.warning("Log folder does not exists. Creating...")
            os.makedirs(LOG_FOLDER)
            log.info("Created!")
        except Exception as err:
            print("Error happened during log folder creating")
            print(repr(err))
            print("Cannot continue, sorry")
            sys.exit(1)

    fh = handlers.RotatingFileHandler(os.path.join(LOG_FOLDER,
                                                   "adapt-info-back.log"),
                                      maxBytes=(1024 * 100),
                                      backupCount=10)
    fh_format = logging.Formatter(
        "%(asctime)s - [%(threadName)s] - %(name)s - [%(levelname)s] - %(message)s"
    )
    fh.setFormatter(fh_format)
    log.addHandler(fh)

    app = web.Application(middlewares=(web.normalize_path_middleware(),
                                       cors_factory, auth_middleware))
    packages = ["api"]
    for route in get_routes(packages):
        app.router.add_route(*route)
    healthcheck = HealthCheck()
    app.router.add_get("/api/healthcheck", healthcheck)

    app.internal_api_token = TOKEN
    # app.router.add_static("/static", STATIC_PATH, name="static")

    log.info("server started!")

    web.run_app(app, host=HOST, port=PORT)
def HomePageView(request):
    if request.method == "POST":
        file = request.FILES.get('upload_file')
        if file:
            temp_file = tempfile.NamedTemporaryFile(delete=False)
            #my_path='C:/Users/saran/Desktop/name.txt'
            with open(temp_file.name, 'wb+') as destination:
                for chunk in file.chunks():
                    destination.write(chunk)
            nodes, edges = parse_file(temp_file.name)
            try:
                Edge.objects.all().delete()
            except:
                pass
            try:
                Node.objects.all().delete()
            except:
                pass

            for i in nodes:
                name = i['name']
                lat_lon = Point(i['lon'], i['lat'])
                Node.objects.create(name=name, location=lat_lon)
            for i in edges:
                origin = i[0]
                destination = i[1]
                distance = i[2]

                #Edge.objects.create(origin_id=origin, destination_id=destination)
                ori = Node.objects.all()[origin - 1]
                des = Node.objects.all()[destination - 1]
                Edge.objects.create(origin=ori, destination=des)

        #t1=nodes[0]
        #print t1
        #print edges[0]

    routes = get_routes(SOURCE, DESTINATION)
    routes = get_node_names(routes)

    try:
        route_index = int(request.GET.get("route_index"))
    except:
        route_index = 0

    #return render(request, "html/upload.html")
    return render(request, 'html/index.html', {
        'routes': routes,
        'route_index': route_index
    })
Exemple #3
0
    def __init__(self, dc_path, dk_path=None):
        self.ctx = SSL.Context(SSL.TLSv1_2_METHOD)
        self.ctx.set_tlsext_servername_callback(self.pick_certificate)
        self.tls_ctx = None
        self.routes = utils.get_routes()

        dk_path = dk_path or dc_path
        if os.path.exists(dk_path) and os.path.exists(dc_path):
            ctx = SSL.Context(SSL.TLSv1_2_METHOD)
            ctx.use_privatekey_file(dk_path)
            ctx.use_certificate_file(dc_path)
            ctx.use_certificate_chain_file(dc_path)
            self.tls_ctx = ctx
        else:
            raise Exception("Unable to load TLS certificate information")
def route_datasets(request):
    routes = get_routes(SOURCE, DESTINATION)
    #print routes

    try:
        route = routes[int(request.GET.get("route_index"))]
    except:
        route = routes[0]
    edges = get_edges(route)

    #route = [1, 2, 5, 4, 7, 6, 3, 9, 8, 10]
    #edges = get_edges_by_index(route)

    #edges = Edge.objects.all()[:5]
    edges = serialize('geojson', edges)
    return HttpResponse(edges, content_type='json')
Exemple #5
0
    def __init__(self, *args, **kwargs):
        self.filesroot = os.path.abspath(os.path.join("files"))
        self.routes = utils.get_routes()

        super().__init__(*args, **kwargs)
Exemple #6
0
    def __init__(self, *args, **kwargs):
        self.routes = utils.get_routes()
        self.ipv4_address = utils.get_variables().get("ipv4_address", utils.get_ipv4_address())
        self.ipv6_address = utils.get_variables().get("ipv6_address", utils.get_ipv6_address())

        super().__init__(*args, **kwargs)
from os import listdir
from re import match

from utils import get_routes


def get_api_packages():
    """
    generates a list of API subpackages to get routes from
    this allows to create a API handlers package, provide routes in __init__ file, and not worry about a thing:
    this method will automaticaly find subpackage, extract routes from it, and pass them to application.

    There are 2 requirements to subpackages:
    1. It must be named "vX", where X is a number.
       "v1", "v25" are suitable names. "heyimanapiv2" and "v2++++" are not suitable names

    2. __init__.py of subpackage must provide routes variable with routes to handlers.

    :return: map object of api subpackages names
    """
    return map(
        lambda item: "api.{}".format(item),
        filter(lambda subdir: bool(match(r"^v\d*$", subdir)), listdir("api")))


packages = get_api_packages()
routes = list(get_routes(packages))

__all__ = ["routes"]