1 Star 3 Fork 0

kevinzhang / rust-rocket-diesel-tera-demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

rust-rocket project

相关文档:

开发环境安装

安装windows子系统ubuntu

更新软件安装源 sudo apt update

安装编译环境

sudo apt install build-essential

安装数据库

  • 安装postgresql数据库 sudo apt install postgresql

安装rocket的数据库工具diesel

diesel支持的数据库类型有:mysqlsqlite3postgresql

默认安装

  • 如果默认安装,需要把这三个数据库的dev lib都安装上:
sudo apt install libsqlite3-dev libpq-dev libmysqlclient-dev
  • 然后安装diesel-cli
cargo install diesel_cli

特征安装

  • 只需要安装需要的dev lib,例如此项目我们使用postgresql数据库:
sudo apt install libpq-dev
  • 然后安装diesel-cli
cargo install diesel_cli --no-default-features --features postgres

安装postgresql数据库

安装

  • 安装数据库
sudo apt install postgresql postgresql-client
  • 安装完后系统会创建一个数据库超级用户postgres,密码为空,下面命令登录此数据库用户
kevin@COMP-ZJF:~/rust/mmd3$ sudo -i -u postgres
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.72-microsoft-standard-WSL2 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Thu Apr 29 11:35:29 CST 2021

  System load:  0.0                Processes:             26
  Usage of /:   2.3% of 250.98GB   Users logged in:       0
  Memory usage: 6%                 IPv4 address for eth0: 172.19.65.53
  Swap usage:   0%

59 updates can be installed immediately.
24 of these updates are security updates.
To see these additional updates run: apt list --upgradable


*** System restart required ***

This message is shown once a day. To disable it please create the
/var/lib/postgresql/.hushlogin file.
postgres@COMP-ZJF:~$
  • 查看是否安装成功,显示以下表示安装成功
postgres@COMP-ZJF:~$ psql
psql (12.6 (Ubuntu 12.6-0ubuntu0.20.04.1))
Type "help" for help.

postgres=#
  • 启动、重启、停止
sudo /etc/init.d/postgresql start   # 开启
sudo /etc/init.d/postgresql stop    # 关闭
sudo /etc/init.d/postgresql restart # 重启
  • 键入\q退出数据库管理界面
postgres=# \q
postgres@COMP-ZJF:~$
  • 切换回系统用户
postgres@COMP-ZJF:~$ su kevin
Password:
kevin@COMP-ZJF:/var/lib/postgresql$

设置密码

  • 删除postgres用户的密码
sudo passwd -d postgres
  • 设置postgress用户的密码,新密码设置为postgres方便记忆,根据自己的实际情况设置
kevin@COMP-ZJF:~/rust/mmd3$ sudo -u postgres passwd
New password:
Retype new password:
passwd: password updated successfully

Rocket项目初始化

编译环境设置

由于rocket需要在rustup nightly的编译环境,因此,需要设置编译环境。

全局设置 nightly环境:

rustup default nightly

单个项目设置nightly环境:

rustup override set nightly

新建rust项目

crate new mmd3

添加项目依赖

更新配置文件Cargo.toml

[package]
name = "mmd3"
version = "0.1.0"
authors = ["kevinjfzhang <kevinjfzhang@sina.com>"]
edition = "2018"

[dependencies]
rocket = "0.4.7"
diesel = { version = "1.4.4", features = ["postgres"] }
dotenv = "0.15.0"

编译:

cargo run

显示下面信息表示项目编译成功:

kevin@COMP-ZJF:~/rust/mmd3$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.16s
     Running `target/debug/mmd3`
Hello, world!

简单路由

编辑main.rs文件

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    "Hello world!"
}

fn main() {
    rocket::ignite()
        .mount("/", routes!(index))
        .launch();
}

运行项目cargo run

kevin@COMP-ZJF:~/rust/mmd3$ cargo run
   Compiling mmd3 v0.1.0 (/home/kevin/rust/mmd3)
    Finished dev [unoptimized + debuginfo] target(s) in 5.54s
     Running `target/debug/mmd3`
🔧 Configured for development.
    => address: localhost
    => port: 8000
    => log: normal
    => workers: 8
    => secret key: generated
    => limits: forms = 32KiB
    => keep-alive: 5s
    => read timeout: 5s
    => write timeout: 5s
    => tls: disabled
🛰   Mounting /:
    => GET / (index)
🚀 Rocket has launched from http://localhost:8000

访问localhost:8000浏览器显示

Hello world!

数据库初始化

创建数据库配置文件,会在项目根目录生成文件.env

echo DATABASE_URL=postgres://postgres:password@localhost:5432/mmd3 > .env

创建数据库

kevin@COMP-ZJF:~/rust/mmd3$ diesel setup
Creating database: mmd3

错误一,表示数据库还没安装或者没有配置好,请返回以上数据库安装章节查看或自行解决

kevin@COMP-ZJF:~/rust/mmd3$ diesel setup
Creating migrations directory at: /home/kevin/rust/mmd3/migrations
Creating database: mmd3
could not connect to server: Connection refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?

错误二,表示配置的密码不正确或者认证文件没有设置为trust,请返回以下数据库安装章节查看如何设置密码

kevin@COMP-ZJF:~/rust/mmd3$ diesel setup
Creating database: mmd3
FATAL:  password authentication failed for user "postgres"
FATAL:  password authentication failed for user "postgres"

更改配置文件.env的密码

DATABASE_URL=postgres://postgres:postgres@localhost:5432/mmd3

重试diesel setup还是一样的错误

kevin@COMP-ZJF:~/rust/mmd3$ diesel setup
Creating database: mmd3
FATAL:  password authentication failed for user "postgres"
FATAL:  password authentication failed for user "postgres"

那么再尝试修改认证文件/var/lib/pgsql/data/pg_hba.conf此文件的路径未必与此一致,请先查找文件的正确路径

kevin@COMP-ZJF:~/rust/mmd3$ sudo find / -name pg_hba.conf
/etc/postgresql/12/main/pg_hba.conf

编辑认证文件前

kevin@COMP-ZJF:~/rust/mmd3$ sudo cat /etc/postgresql/12/main/pg_hba.conf
# DO NOT DISABLE!
# If you change this first entry you will need to make sure that the
# database superuser can access the database using some other method.
# Noninteractive access to all databases is required during automatic
# maintenance (custom daily cronjobs, replication, and similar tasks).
#
# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5

编辑认证文件后

kevin@COMP-ZJF:~/rust/mmd3$ sudo cat /etc/postgresql/12/main/pg_hba.conf
# DO NOT DISABLE!
# If you change this first entry you will need to make sure that the
# database superuser can access the database using some other method.
# Noninteractive access to all databases is required during automatic
# maintenance (custom daily cronjobs, replication, and similar tasks).
#
# Database administrative login by Unix domain socket
local   all             postgres                                trust

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     trust
host    replication     all             127.0.0.1/32            trust
host    replication     all             ::1/128                 trust

重启服务器,然后重新运行命令diesel setup

sudo /etc/init.d/postgresql restart

到此,项目文件目录为

kevin@COMP-ZJF:~/rust/mmd3$ tree -L 3
.
├── Cargo.lock
├── Cargo.toml
├── diesel.toml
├── migrations
│   └── 00000000000000_diesel_initial_setup
│       ├── down.sql
│       └── up.sql
├── src
│   └── main.rs
└── target
    ├── CACHEDIR.TAG
    └── debug
        ├── build
        ├── deps
        ├── examples
        ├── incremental
        ├── mmd3
        └── mmd3.d

创建文件夹:src/dbsrc/modelssrc/routers

创建文件:src/lib.rs

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate diesel;

// 数据库模块
pub mod db;
// 模型模块
pub mod models;
// 路由模块
pub mod routers;

路由分组

目录结构

切换到项目src目录并查看目录结构,按照如下目录结构进行路由分组:

kevin@COMP-ZJF:~/rust/mmd3/src$ tree -L 3
.
├── lib.rs
├── main.rs
└── routers
    ├── front
    │   ├── index.rs
    │   └── mod.rs
    ├── mod.rs
    └── system
        ├── category.rs
        └── mod.rs

挂载路由

文件:rc/main.rs

#[macro_use]
extern crate rocket;
extern crate mmd3;

use mmd3::routers::{system, front};

fn main() {
    rocket::ignite()
        // 每个mount方法相当于一个路由组
        .mount("/", routes!(
            front::index::index
        ))  
        .mount("/system", routes!(
            system::category::category_list
        ))
        .launch();
}

路由配置

文件:src/routers/mod.rs

pub mod system;
pub mod front;

system端路由组

文件:src/routers/system/mod.rs

pub mod category;

文件:src/routers/system/category.rs

use rocket::{get};

#[get("/categories")]
pub fn category_list() -> String {
    String::from("hello, router")
}

web端路由组

文件:src/routers/front/mod.rs

pub mod index;

文件:src/routers/front/index.rs

use rocket::{get};

#[get("/")]
pub fn index() -> &'static str {
    "Hello world!"
}

运行项目

kevin@COMP-ZJF:~/rust/mmd3$ cargo run --bin mmd3
   Compiling diesel v1.4.6
   Compiling mmd3 v0.1.0 (/home/kevin/rust/mmd3)
    Finished dev [unoptimized + debuginfo] target(s) in 27.64s
     Running `target/debug/mmd3`
🔧 Configured for development.
    => address: localhost
    => port: 8000
    => log: normal
    => workers: 8
    => secret key: generated
    => limits: forms = 32KiB
    => keep-alive: 5s
    => read timeout: 5s
    => write timeout: 5s
    => tls: disabled
🛰   Mounting /:
    => GET / (index)
🛰   Mounting /system:
    => GET /system/categories (category_list)
🚀 Rocket has launched from http://localhost:8000

Diesel-Cli数据迁移

创建迁移文件

迁移命令会对数据库或表进行操作,生产环境请不要使用,除非你知道风险并知道如何规避对系统造成影响

kevin@COMP-ZJF:~/rust/mmd3$ diesel migration generate categories
Creating migrations/2021-04-29-073021_categories/up.sql
Creating migrations/2021-04-29-073021_categories/down.sql

新生成了diesel.toml文件和migrations文件夹

kevin@COMP-ZJF:~/rust/mmd3$ tree -L 3
.
├── Cargo.lock
├── Cargo.toml
├── diesel.toml	// 新创建
├── migrations	// 新创建
│   ├── 00000000000000_diesel_initial_setup
│   │   ├── down.sql
│   │   └── up.sql
│   └── 2021-04-29-073021_categories
│       ├── down.sql
│       └── up.sql
├── src
│   ├── main.rs
│   └── routers
│       ├── front
│       ├── mod.rs
│       └── system

设置schema.rs的默认位置

更改配置文件diesel.rs

# For documentation on how to configure this file,
# see diesel.rs/guides/configuring-diesel-cli

[print_schema]
file = "src/db/schema.rs"  # 更改前 file = "src/schema.rs"

编辑数据表迁移文件

文件:migrations/2021-04-29-073021_categories/up.sql

CREATE TABLE categories (
    id SERIAL PRIMARY KEY,
    cat_name VARCHAR NOT NULL,
    cat_id INTEGER NOT NULL UNIQUE,
    level INTEGER NOT NULL,
    parent_cat_id INTEGER NOT NULL,
    m_sort INTEGER NOT NULL DEFAULT 9,
    loaded BOOLEAN NOT NULL DEFAULT 'f',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
);

文件:migrations/2021-04-29-073021_categories/down.sql

DROP TABLE categories;

执行数据表迁移

kevin@COMP-ZJF:~/rust/mmd3$ diesel migration run
Running migration 2021-04-29-073021_categories

回滚并执行迁移

如果数据表结构有更改,可以运行命令diesel migration redo重新生成迁移文件

kevin@COMP-ZJF:~/rust/mmd3$ diesel migration redo
Rolling back migration 2021-04-29-073021_categories
Running migration 2021-04-29-073021_categories

数据库连接层

建立连接

编辑文件:src/db/mod.rs

pub mod schema;
pub mod conn;	// 新增

新建文件:src/db/conn.rs

use disel::pg::PgConnection;
use dotenv::dotenv;
use std::env;

pub fn psql() -> PgConnection{
    dotenv().ok();

    let db_url = env::var("DATABASE_URL")
        .expect("DATABASE must be set");
    PgConnection::establish(&db_url)
        .expect(
            &format!("Error connection to {}", db_url)
        )
}

文件目录:

kevin@COMP-ZJF:~/rust/mmd3$ tree -L 3
.
├── Cargo.lock
├── Cargo.toml
├── diesel.toml
├── migrations
│   ├── 00000000000000_diesel_initial_setup
│   │   ├── down.sql
│   │   └── up.sql
│   └── 2021-04-29-073021_categories
│       ├── down.sql
│       └── up.sql
├── src
│   ├── db
│   │   ├── conn.rs
│   │   ├── mod.rs
│   │   └── schema.rs
│   ├── main.rs
│   └── routers
│       ├── front
│       ├── mod.rs
│       └── system

创建模型

新建文件:src/models/mod.rs

pub mod category;

新建文件:src/models/category.rs

use chrono::NaiveDateTime;

#[derive(Queryable)]
pub struct Category {
    pub id: i32,
    pub cat_name: String,
    pub cat_id: i32,
    pub level: i32,
    pub parent_cat_id: i32,
    pub m_sort: i32,
    pub loaded: bool,
    pub created_at: Option<NaiveDateTime>,
    pub updated_at: Option<NaiveDateTime>,
}

安装chronoserde

更改配置文件Cargo.toml依赖

[dependencies]
rocket = "0.4.7"
diesel = { version = "1.4.4", features = ["postgres", "chrono"] }			 # 开启chrono feature
dotenv = "0.15.0"
serde = { version = "1.0", features = ["derive"] }							# 新增,序列化数据
chrono = { version = "0.4", features = ["serde", "rustc-serialize"] }		  # 新增, 处理时间

安装依赖

cargo build

diesel-cli 显示栏目列表

自定义命令

添加文件:src/bin/show_categories

extern crate diesel;
extern crate mmd3;

use self::diesel::prelude::*;
use mmd3::models::category::*;

fn main() {
    use mmd3::db::schema::categories::dsl::*;

    let conn = mmd3::db::conn::psql();
    let results = categories.filter(loaded.eq(true))
        .limit(5)
        .load::<Category>(&conn)
        .expect("Error loading categories");

    println!("Displaying {} categories", results.len());
    for category in results {
        println!("{}", category.cat_name);
        println!("----------\n");
        println!("{}", category.id);
    }
}

运行自定义命令

运行显示栏目列表的功能:

kevin@COMP-ZJF:~/rust/mmd3$ cargo run --bin show_categories
   Compiling mmd3 v0.1.0 (/home/kevin/rust/mmd3)
    Finished dev [unoptimized + debuginfo] target(s) in 3.09s
     Running `target/debug/show_categories`
Displaying 0 categories

Tera模块引擎

编辑配置文件:Cargo.toml

# 添加rocket_contrib
[dependencies.rocket_contrib]
version = "0.4.7"
default-features = false
features = ["tera_templates"]

编辑文件:src/main.rs

#[macro_use]
extern crate rocket;
extern crate mmd3;

use mmd3::routers::{system, front};
use rocket_contrib::templates::Template;	// 添加

fn main() {
    rocket::ignite()
        // 每个mount方法相当于一个路由组
        .mount("/", routes!(
            front::index::index
        ))  
        .mount("/system", routes!(
            system::category::category_list,
            system::dashboard,			// 添加
        ))
        .attach(Template::fairing())     // 添加
        .launch();
}

添加路由:src/routers/system/mod.rs

pub mod category;

use std::collections::HashMap;
use rocket::{get};
use rocket_contrib::{templates::Template};

#[get("/")]
pub fn dashboard() -> Template {
    let mut context = HashMap::new();
    context.insert(String::from("hello"), String::from("Tom and Jerry"));
    Template::render("system/dashboard", &context)
}

添加模板文件:templates/system/dashboard.html.tera

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    {{ hello }}
</body>

</html>

启动:cargo run --bin mmd3

访问:http://localhost:8000/system

浏览器显示:Tom and Jerry

^_^

运用rocket+diesel+postgresql+tera基本的web服务搭建成功,更多的功能可基于此进行扩展。

感谢您的时间,欢迎交流,也欢迎指正错误的地方。

MIT License Copyright (c) 2021 kevinzhang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

rust-rocket-diesel-tera-demo 展开 收起
Rust 等 2 种语言
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Rust
1
https://gitee.com/kevinjfzhang/rust-rocket-diesel-tera-demo.git
git@gitee.com:kevinjfzhang/rust-rocket-diesel-tera-demo.git
kevinjfzhang
rust-rocket-diesel-tera-demo
rust-rocket-diesel-tera-demo
master

搜索帮助