File Uploads

Batman learned how to handle file uploads using Robyn. He created an endpoint to handle file uploads using the following code:

Sending a File without MultiPart Form Data

Batman scaled his application across multiple cores for better performance. He used the following command:

Request

GET
/hello_world
@app.post("/upload")
async def upload():
  body = request.body
  file = bytearray(body)

  # write whatever filename
  with open('test.txt', 'wb') as f:
      f.write(body)

  return {'message': 'success'}

Sending a File with MultiPart Form Data

Batman scaled his application across multiple cores for better performance. He used the following command:

Request

GET
/hello_world

@app.post("/sync/multipart-file")
def sync_multipart_file(request: Request):
    files = request.files
    file_names = files.keys()
    return {"file_names": list(file_names)}

File Downloads

Batman now wanted to allow users to download files from his application. He created an endpoint to handle file downloads using the following code:

Serving Simple HTML Files

Batman scaled his application across multiple cores for better performance. He used the following command:

Request

GET
/hello_world
from robyn import Robyn, serve_html

app = Robyn(__file__)


@app.get("/")
async def h(request):
    return serve_html("./index.html")

app.start(port=8080)

Serving simple HTML strings

Speaking of HTML files, Batman wanted to serve simple HTML strings. He was suggested to use the following code:

Request

GET
/hello_world
from robyn import Robyn, html

app = Robyn(__file__)


@app.get("/")
async def h(request):
    html_string = "<h1>Hello World</h1>"
    return html(html_string)

app.start(port=8080)

Serving Other Files

Batman scaled his application across multiple cores for better performance. He used the following command:

Request

GET
/hello_world
from robyn import Robyn, serve_file

app = Robyn(__file__)


@app.get("/")
async def h(request):
    return serve_file("./index.html", file_name="index.html") # file_name is optional

app.start(port=8080)

What's next?

Now, Batman was ready to learn about the advanced features of Robyn. He wanted to find a way to handle form data