Question:
So in my framework I am making I am trying to clean up app.py
and move the functions to framework.py
, it throws this error →
Traceback (most recent call last):
File "/home/runner/VIAL/app.py", line 2, in <mod ule>
from sre import App, route, tags, Response File "/home/runner/VIAL/src/__init__.py", line 4 , in ‹module>
from . framework import route
ImportError: cannot import name 'route' from 'src. framework' (/home/runner/VIAL/src/framework.py)
Repl link:
https://replit.com/@SalladShooter/VIAL
app.py
# app.py
from src import App, route, tags, Response
class MyApp(App):
def index(self, request):
css_link = '<link rel="stylesheet" type="text/css" href="/static/styles.css">'
js_link = '<script src="/static/script.js"></script>'
html_content = css_link + js_link
list_items = [
tags.li("Item 1"),
tags.li("Item 2"),
tags.li("Item 3")
]
html_content += str(tags.ul().add_children(*list_items))
html_content += str(tags.p("Hello, World!").attribute('class', 'p').id('p').add_children(tags.div()))
return Response(html_content, content_type='text/html')
framework.py
# framework.py
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule # Adding the import for Rule
class Request(Request):
pass
class Response(Response):
pass
class App:
def __init__(self):
self.routes = {}
self.url_map = Map() # Creating a url_map for routing
def route(self, rule, **kwargs):
def decorator(f):
kwargs['endpoint'] = f.__name__
self.url_map.add(Rule(rule, **kwargs))
return f
return decorator
def dispatch_request(self, request):
view_func = self.routes.get(request.path)
if view_func is not None:
return view_func(request)
return Response('Not Found', status=404)
def __call__(self, environ, start_response):
request = Request(environ)
response = self.dispatch_request(request)
return response(environ, start_response)
__init__.py
# Copyright (c) 2024 SalladShooter
from .framework import App, Response
from .framework import route
from .framework import dispatch_request, __call__
from .html_generator import *
__all__ = ['App', 'route', 'tags', 'Response', 'dispatch_request', '__call__'] ```