Web Frameworks
Objective: Implement simple web application that demonstrates how to parse URL and how web framework handes errors. Use built-in HTTP servers.
Python
Framework in use: flask.
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=["GET"]) # methods=["GET"] can be skipped, it is default
def hello_world():
return f"Hello, World!"
@app.route('/bug')
def hello_bug():
# let's see how it is rendered in debug mode
raise Exception("Intentional error")
@app.route('/<name>')
def hello(name):
name = name or "World"
return f"Hello, {name}!"
if __name__ == "__main__":
app.run(port=3000, debug=True)
Rust
Framework in use: actix-web.
use actix_web::{get, web, App, HttpServer, Responder}; #[get("/")] async fn hello_world() -> impl Responder { "Hello World!" } #[get("/bug")] async fn hello_bug() -> actix_web::Result<String> { Err(actix_web::error::ErrorNotImplemented("Intentional error")) } #[get("/{name}")] async fn hello(name: web::Path<String>) -> impl Responder { format!("Hello {}!", &name) } #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| App::new() .service(hello_world) .service(hello_bug) .service(hello)) .bind(("127.0.0.1", 3000))? .run() .await }
Crystal
Framework in use: kemal.
require "kemal"
get "/" do
"Hello World!"
end
get "/bug" do
raise "Intentional error"
end
get "/:name" do |env|
name = env.params.url["name"]
"Hello #{name}!"
end
Kemal.run