mirror of
https://github.com/actix/examples
synced 2024-11-23 22:41:07 +01:00
rename web::State to web::Data
This commit is contained in:
parent
14eed91fcd
commit
b31c8e3308
@ -9,8 +9,8 @@ use crate::db;
|
|||||||
use crate::session::{self, FlashMessage};
|
use crate::session::{self, FlashMessage};
|
||||||
|
|
||||||
pub fn index(
|
pub fn index(
|
||||||
pool: web::State<db::PgPool>,
|
pool: web::Data<db::PgPool>,
|
||||||
tmpl: web::State<Tera>,
|
tmpl: web::Data<Tera>,
|
||||||
session: Session,
|
session: Session,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
web::block(move || db::get_all_tasks(&pool))
|
web::block(move || db::get_all_tasks(&pool))
|
||||||
@ -45,7 +45,7 @@ pub struct CreateForm {
|
|||||||
|
|
||||||
pub fn create(
|
pub fn create(
|
||||||
params: web::Form<CreateForm>,
|
params: web::Form<CreateForm>,
|
||||||
pool: web::State<db::PgPool>,
|
pool: web::Data<db::PgPool>,
|
||||||
session: Session,
|
session: Session,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
if params.description.is_empty() {
|
if params.description.is_empty() {
|
||||||
@ -86,7 +86,7 @@ pub struct UpdateForm {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn update(
|
pub fn update(
|
||||||
db: web::State<db::PgPool>,
|
db: web::Data<db::PgPool>,
|
||||||
params: web::Path<UpdateParams>,
|
params: web::Path<UpdateParams>,
|
||||||
form: web::Form<UpdateForm>,
|
form: web::Form<UpdateForm>,
|
||||||
session: Session,
|
session: Session,
|
||||||
@ -102,7 +102,7 @@ pub fn update(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn toggle(
|
fn toggle(
|
||||||
pool: web::State<db::PgPool>,
|
pool: web::Data<db::PgPool>,
|
||||||
params: web::Path<UpdateParams>,
|
params: web::Path<UpdateParams>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
web::block(move || db::toggle_task(params.id, &pool))
|
web::block(move || db::toggle_task(params.id, &pool))
|
||||||
@ -114,7 +114,7 @@ fn toggle(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn delete(
|
fn delete(
|
||||||
pool: web::State<db::PgPool>,
|
pool: web::Data<db::PgPool>,
|
||||||
params: web::Path<UpdateParams>,
|
params: web::Path<UpdateParams>,
|
||||||
session: Session,
|
session: Session,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
|
@ -21,7 +21,7 @@ use db::{Pool, Queries, WeatherAgg};
|
|||||||
|
|
||||||
/// Version 1: Calls 4 queries in sequential order, as an asynchronous handler
|
/// Version 1: Calls 4 queries in sequential order, as an asynchronous handler
|
||||||
fn asyncio_weather(
|
fn asyncio_weather(
|
||||||
db: web::State<Pool>,
|
db: web::Data<Pool>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = AWError> {
|
) -> impl Future<Item = HttpResponse, Error = AWError> {
|
||||||
let mut result: Vec<Vec<WeatherAgg>> = vec![];
|
let mut result: Vec<Vec<WeatherAgg>> = vec![];
|
||||||
|
|
||||||
@ -52,7 +52,7 @@ fn asyncio_weather(
|
|||||||
/// Version 2: Calls 4 queries in parallel, as an asynchronous handler
|
/// Version 2: Calls 4 queries in parallel, as an asynchronous handler
|
||||||
/// Returning Error types turn into None values in the response
|
/// Returning Error types turn into None values in the response
|
||||||
fn parallel_weather(
|
fn parallel_weather(
|
||||||
db: web::State<Pool>,
|
db: web::Data<Pool>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = AWError> {
|
) -> impl Future<Item = HttpResponse, Error = AWError> {
|
||||||
let fut_result = vec![
|
let fut_result = vec![
|
||||||
Box::new(db::execute(&db, Queries::GetTopTenHottestYears)),
|
Box::new(db::execute(&db, Queries::GetTopTenHottestYears)),
|
||||||
|
@ -24,7 +24,7 @@ type Pool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
|
|||||||
/// Diesel query
|
/// Diesel query
|
||||||
fn query(
|
fn query(
|
||||||
nm: String,
|
nm: String,
|
||||||
pool: web::State<Pool>,
|
pool: web::Data<Pool>,
|
||||||
) -> Result<models::User, diesel::result::Error> {
|
) -> Result<models::User, diesel::result::Error> {
|
||||||
use self::schema::users::dsl::*;
|
use self::schema::users::dsl::*;
|
||||||
|
|
||||||
@ -44,7 +44,7 @@ fn query(
|
|||||||
/// Async request handler
|
/// Async request handler
|
||||||
fn add(
|
fn add(
|
||||||
name: web::Path<String>,
|
name: web::Path<String>,
|
||||||
pool: web::State<Pool>,
|
pool: web::Data<Pool>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
// run diesel blocking code
|
// run diesel blocking code
|
||||||
web::block(move || query(name.into_inner(), pool)).then(|res| match res {
|
web::block(move || query(name.into_inner(), pool)).then(|res| match res {
|
||||||
@ -63,7 +63,7 @@ const MAX_SIZE: usize = 262_144; // max payload size is 256k
|
|||||||
/// This handler manually load request payload and parse json object
|
/// This handler manually load request payload and parse json object
|
||||||
fn index_add<P>(
|
fn index_add<P>(
|
||||||
pl: web::Payload<P>,
|
pl: web::Payload<P>,
|
||||||
pool: web::State<Pool>,
|
pool: web::Data<Pool>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error>
|
) -> impl Future<Item = HttpResponse, Error = Error>
|
||||||
where
|
where
|
||||||
P: Stream<Item = Bytes, Error = error::PayloadError>,
|
P: Stream<Item = Bytes, Error = error::PayloadError>,
|
||||||
@ -110,7 +110,7 @@ where
|
|||||||
|
|
||||||
fn add2(
|
fn add2(
|
||||||
item: web::Json<MyUser>,
|
item: web::Json<MyUser>,
|
||||||
pool: web::State<Pool>,
|
pool: web::Data<Pool>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
// run diesel blocking code
|
// run diesel blocking code
|
||||||
web::block(move || query(item.into_inner().name, pool)).then(|res| match res {
|
web::block(move || query(item.into_inner().name, pool)).then(|res| match res {
|
||||||
|
@ -45,7 +45,7 @@ fn handle_post_1(params: web::Form<MyParams>) -> Result<HttpResponse> {
|
|||||||
|
|
||||||
/// State and POST Params
|
/// State and POST Params
|
||||||
fn handle_post_2(
|
fn handle_post_2(
|
||||||
state: web::State<AppState>,
|
state: web::Data<AppState>,
|
||||||
params: web::Form<MyParams>,
|
params: web::Form<MyParams>,
|
||||||
) -> HttpResponse {
|
) -> HttpResponse {
|
||||||
HttpResponse::Ok().content_type("text/plain").body(format!(
|
HttpResponse::Ok().content_type("text/plain").body(format!(
|
||||||
|
@ -24,7 +24,7 @@ fn graphiql() -> HttpResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn graphql(
|
fn graphql(
|
||||||
st: web::State<Arc<Schema>>,
|
st: web::Data<Arc<Schema>>,
|
||||||
data: web::Json<GraphQLRequest>,
|
data: web::Json<GraphQLRequest>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
web::block(move || {
|
web::block(move || {
|
||||||
|
@ -10,7 +10,7 @@ use uuid;
|
|||||||
/// Async request handler. Ddb pool is stored in application state.
|
/// Async request handler. Ddb pool is stored in application state.
|
||||||
fn index(
|
fn index(
|
||||||
path: web::Path<String>,
|
path: web::Path<String>,
|
||||||
db: web::State<Pool<SqliteConnectionManager>>,
|
db: web::Data<Pool<SqliteConnectionManager>>,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
// execute sync code in threadpool
|
// execute sync code in threadpool
|
||||||
web::block(move || {
|
web::block(move || {
|
||||||
|
@ -1,12 +1,12 @@
|
|||||||
#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
|
#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
|
||||||
//! Application may have multiple states that are shared across
|
//! Application may have multiple data objects that are shared across
|
||||||
//! all handlers within same Application. State could be added
|
//! all handlers within same Application. Data could be added
|
||||||
//! with `App::state()` method, multiple different states could be added.
|
//! with `App::data()` method, multiple different data objects could be added.
|
||||||
//!
|
//!
|
||||||
//! > **Note**: http server accepts an application factory rather than an
|
//! > **Note**: http server accepts an application factory rather than an
|
||||||
//! application > instance. Http server constructs an application instance for
|
//! application > instance. Http server constructs an application instance for
|
||||||
//! each thread, > thus application state
|
//! each thread, > thus application data
|
||||||
//! > must be constructed multiple times. If you want to share state between
|
//! > must be constructed multiple times. If you want to share data between
|
||||||
//! different > threads, a shared object should be used, e.g. `Arc`.
|
//! different > threads, a shared object should be used, e.g. `Arc`.
|
||||||
//!
|
//!
|
||||||
//! Check [user guide](https://actix.rs/book/actix-web/sec-2-application.html) for more info.
|
//! Check [user guide](https://actix.rs/book/actix-web/sec-2-application.html) for more info.
|
||||||
@ -17,7 +17,7 @@ use std::sync::{Arc, Mutex};
|
|||||||
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
|
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
|
||||||
|
|
||||||
/// simple handle
|
/// simple handle
|
||||||
fn index(state: web::State<Arc<Mutex<usize>>>, req: HttpRequest) -> HttpResponse {
|
fn index(state: web::Data<Arc<Mutex<usize>>>, req: HttpRequest) -> HttpResponse {
|
||||||
println!("{:?}", req);
|
println!("{:?}", req);
|
||||||
*(state.lock().unwrap()) += 1;
|
*(state.lock().unwrap()) += 1;
|
||||||
|
|
||||||
@ -33,7 +33,7 @@ fn main() -> io::Result<()> {
|
|||||||
//move is necessary to give closure below ownership of counter
|
//move is necessary to give closure below ownership of counter
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.state(counter.clone()) // <- create app with shared state
|
.data(counter.clone()) // <- create app with shared state
|
||||||
// enable logger
|
// enable logger
|
||||||
.middleware(middleware::Logger::default())
|
.middleware(middleware::Logger::default())
|
||||||
// register simple handler, handle all methods
|
// register simple handler, handle all methods
|
||||||
|
@ -7,7 +7,7 @@ use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer};
|
|||||||
|
|
||||||
// store tera template in application state
|
// store tera template in application state
|
||||||
fn index(
|
fn index(
|
||||||
tmpl: web::State<tera::Tera>,
|
tmpl: web::Data<tera::Tera>,
|
||||||
query: web::Query<HashMap<String, String>>,
|
query: web::Query<HashMap<String, String>>,
|
||||||
) -> Result<HttpResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let s = if let Some(name) = query.get("name") {
|
let s = if let Some(name) = query.get("name") {
|
||||||
|
Loading…
Reference in New Issue
Block a user