sparckles / Robyn

Robyn is a Super Fast Async Python Web Framework with a Rust runtime.
https://robyn.tech/
BSD 2-Clause "Simplified" License
4.41k stars 229 forks source link

[Feature Request] Allow the ability of sending the headers from the same route #325

Closed sansyrox closed 1 year ago

sansyrox commented 1 year ago

Current Behavior

Currently, you cannot send the custom headers in the response from you route. Add the ability to do that.

Desired Behavior

Something along these lines, from our discussion on discord with @cirospaciari

@app.get('/plaintext')
def plaintext() -> str:
    return { "body": "Hello, world!", "headers": { "Content-Type": "plain/text", "Custom": "My Custom Value" }}  

Screenshots / Mockups

Alternatives


sansyrox commented 1 year ago

This already existed. Just needed to document! :(

cirospaciari commented 1 year ago

Just adding the example of headers using jsonify

@app.get("/redirect")
async def redirect(request):
    return {
        "status_code": "307",
        "body": "",
        "type": "text",
        "headers": jsonify({"Location": "redirect_route"}),
    }
sansyrox commented 1 year ago

Thank you @cirospaciari 😄

cirospaciari commented 1 year ago

Helper example:

def redirect(location: str, status_code:int = 302):
    return {
        "status_code": str(status_code),
        "body": "",
        "type": "text",
        "headers": jsonify({"Location": location}),
    }

Usage:

from helpers import redirect

@app.get("/")
def home(request):
    ... some login logic here ...
    if needs_login:
       return redirect("/login")
    ... normal flow here ....

@app.get("/someroute")
def some_route(request):
    return redirect("/", 301) # 301 Moved Permanently
cirospaciari commented 1 year ago

I don't know why jsonify is needed, I think is just more overhead and also status_code should be int not str, unless you want to send the full status message like "200 OK" this is how socketify.py does:

def home(res, req):
     res.redirect("/", 301)  # 301 Moved Permanently

def home(res, req):
     res.write_status("403 Forbidden").end("Forbidden")   

def home(res, req):
     res.write_status(403).end("Forbidden")   

Status 200 OK is the default.

I think an refactor should allow it to be like:

def redirect(location: str, status_code:int = 302):
    return {
        "status_code":  status_code,
        "headers": {"Location": location},
    }

or using tuples instead of dict as an option.

sansyrox commented 1 year ago

@cirospaciari , thank you for the examples.

I don't know why jsonify is needed, I think is just more overhead and also status_code should be int not str, unless you want to send the full status message like "200 OK" this is how socketify.py does:

This is a limitation at the moment. This will need to be fixed. And this will also possibly increase a lot of speed issues.