相关文档:
ubuntu
更新软件安装源 sudo apt update
sudo apt install build-essential
postgresql
数据库 sudo apt install postgresql
rocket
的数据库工具diesel
diesel支持的数据库类型有:mysql
,sqlite3
,postgresql
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需要在rustup nightly
的编译环境,因此,需要设置编译环境。
全局设置 nightly环境:
rustup default nightly
单个项目设置nightly环境:
rustup override set nightly
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/db
,src/models
,src/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;
文件: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")
}
文件: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
迁移命令会对数据库或表进行操作,生产环境请不要使用,除非你知道风险并知道如何规避对系统造成影响
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>,
}
chrono
和serde
更改配置文件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
添加文件: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
编辑配置文件: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服务搭建成功,更多的功能可基于此进行扩展。
感谢您的时间,欢迎交流,也欢迎指正错误的地方。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。