Skip to content

Commit

Permalink
Add support for warp
Browse files Browse the repository at this point in the history
  • Loading branch information
aeons committed Jan 23, 2020
1 parent db2e6a2 commit 6677c81
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 2 deletions.
3 changes: 3 additions & 0 deletions askama/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ with-iron = ["iron", "askama_derive/iron"]
with-rocket = ["rocket", "askama_derive/rocket"]
with-actix-web = ["actix-web", "askama_derive/actix-web", "mime", "mime_guess", "bytes", "futures"]
with-gotham = ["gotham", "askama_derive/gotham", "hyper", "mime", "mime_guess"]
with-warp = ["warp", "askama_derive/warp", "mime", "mime_guess"]

[dependencies]
askama_derive = { version = "0.9.0", path = "../askama_derive" }
Expand All @@ -42,6 +43,8 @@ mime_guess = { version = "2.0.0-alpha", optional = true }
gotham = { version = "0.3", optional = true }
hyper = { version = "0.12", optional = true }
bytes = { version = "0.5", optional = true }
warp = { version = "0.2", optional = true }
http = { version = "0.2", optional = true }

[package.metadata.docs.rs]
features = ["config", "humansize", "num-traits", "serde-json", "serde-yaml"]
29 changes: 29 additions & 0 deletions askama/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,13 @@
//! signature, with a status code of `500 Internal Server Error`, mime `*/*`, and an empty `Body`.
//! This preserves the response chain if any custom error handling needs to occur.
//!
//! ## Warp integration
//!
//! Enabling the `with-warp` feature appends an implementation of Warp's `Reply`
//! trait for each template type. This makes it simple to return a template from
//! a Warp filter. See [the example](https://github.com/djc/askama/blob/master/testing/tests/warp.rs)
//! from the Askama test suite for more on how to integrate.
//!
//! ## The `json` filter
//!
//! Enabling the `serde-json` filter will enable the use of the `json` filter.
Expand All @@ -480,6 +487,7 @@
#![allow(unused_imports)]
#[macro_use]
extern crate askama_derive;

pub use askama_shared as shared;

use std::fs::{self, DirEntry};
Expand Down Expand Up @@ -627,6 +635,27 @@ pub mod gotham {
}
}

#[cfg(feature = "with-warp")]
pub mod warp {
use warp::http::{self, header, StatusCode};
use warp::hyper::Body;
pub use warp::reply::{Reply, Response};

pub fn reply<T: super::Template>(t: &T, ext: &str) -> Response {
let mime_type = super::get_mime_type(ext);
match t.render() {
Ok(body) => http::Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, mime_type.essence_str())
.body(body.into()),
Err(_) => http::Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::empty()),
}
.unwrap()
}
}

/// Old build script helper to rebuild crates if contained templates have changed
///
/// This function is now deprecated and does nothing.
Expand Down
1 change: 1 addition & 0 deletions askama_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ iron = []
rocket = []
actix-web = []
gotham = []
warp = []

[dependencies]
askama_shared = { version = "0.9", path = "../askama_shared" }
Expand Down
17 changes: 17 additions & 0 deletions askama_derive/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ impl<'a> Generator<'a> {
if cfg!(feature = "gotham") {
self.impl_gotham_into_response(&mut buf);
}
if cfg!(feature = "warp") {
self.impl_warp_reply(&mut buf);
}
buf.buf
}

Expand Down Expand Up @@ -272,6 +275,20 @@ impl<'a> Generator<'a> {
buf.writeln("}");
}

fn impl_warp_reply(&mut self, buf: &mut Buffer) {
self.write_header(buf, "::askama::warp::Reply", None);
buf.writeln("fn into_response(self) -> ::askama::warp::Response {");
let ext = self
.input
.path
.extension()
.and_then(|s| s.to_str())
.unwrap_or("txt");
buf.writeln(&format!("::askama::warp::reply(&self, {:?})", ext));
buf.writeln("}");
buf.writeln("}");
}

// Writes header for the `impl` for `TraitFromPathName` or `Template`
// for the given context struct.
fn write_header(
Expand Down
4 changes: 4 additions & 0 deletions testing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ serde-json = ["serde_json", "askama/serde-json"]
with-rocket = ["rocket", "askama/with-rocket"]
with-iron = ["iron", "askama/with-iron"]
with-gotham = ["gotham", "askama/with-gotham", "mime", "hyper"]
with-warp = ["warp", "askama/with-warp", "tokio", "tokio-test"]

[dependencies]
actix-web = { version = "2", optional = true }
Expand All @@ -26,6 +27,9 @@ serde_json = { version = "1.0", optional = true }
gotham = { version = "0.3", optional = true }
mime = { version = "0.3", optional = true }
hyper = { version = "0.12", optional = true }
warp = { version = "0.2", optional = true }
tokio-test = { version = "0.2", optional = true }
tokio = { version = "0.2", optional = true, features = ["macros"] }

[dev-dependencies]
criterion = "0.3"
Expand Down
4 changes: 2 additions & 2 deletions testing/tests/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,9 @@ fn test_option() {

#[derive(Template)]
#[template(path = "generics.html")]
struct GenericsTemplate<T: std::fmt::Display, U = u8>
struct GenericsTemplate<T: std::fmt::Display + std::marker::Send, U = u8>
where
U: std::fmt::Display,
U: std::fmt::Display + std::marker::Send,
{
t: T,
u: U,
Expand Down
20 changes: 20 additions & 0 deletions testing/tests/warp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#![cfg(feature = "with-warp")]

use askama::Template;
use warp::Filter;

#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate<'a> {
name: &'a str,
}

#[tokio::test]
async fn test_warp() {
let filter = warp::get().map(|| HelloTemplate { name: "world" });

let res = warp::test::request().reply(&filter).await;

assert_eq!(res.status(), 200);
assert_eq!(res.body(), "Hello, world!");
}

0 comments on commit 6677c81

Please sign in to comment.