cutelyst教程_02 _Cutelyst基础

Tutorial_02_CutelystBasics

教程_02 _Cutelyst基础

Daniel Nicoletti edited this page on May 8, 2020 · 14 revisions

​Daniel Nicoletti在2020年5月8日第14次修订时编辑了本页

 OVERVIEW

总览

  1. Introduction
  2. Cutelyst Basics
  3. More Cutelyst Basics
  4. Basic CRUD
  5. Authentication

DESCRIPTION

说明

In this chapter of the tutorial, we will create a very basic Cutelyst web application, demonstrating a number of powerful capabilities, such as:

在本教程的这一章中,我们将创建一个非常基本的Cutelyst web应用程序,展示一些强大的功能,例如:

Developer Helper Command

开发者助手命令

Cutelyst developer helper command that can be used to rapidly bootstrap the skeletal structure of an application.

Cutelyst developer 助手命令,可用于快速构建应用程序的框架结构。

MVC Model/View/Controller (MVC) provides an architecture that facilitates a clean "separation of control" between the different portions of your application. Given that many other documents cover this subject in detail, MVC will not be discussed in depth here. In short:

MVC Model/View/Controller(MVC)提供了一种架构,有助于在应用程序的不同部分之间实现清晰的“控制分离”。鉴于许多其他文档都详细介绍了这个主题,这里将不深入讨论MVC。简而言之:

Model The model usually represents a data store. In most applications, the model equates to the objects that are created from and saved to your SQL database. Currently Cutelyst doesn't have a clear definition to models, QAbstractItemModel might end up being used to fill this MVC gap.

Model 模型通常表示一个数据存储。在大多数应用程序中,模型等同于从SQL数据库创建并保存到SQL数据库的对象。目前Cutelyst对模型没有明确的定义,QAbstractItemModel可能最终被用来填补MVC的空白。

View The view takes stash / model objects and renders them into something for the end user to look at. Normally this involves a template-generation tool that creates HTML for the user's web browser, but it could easily be code that generates other forms such as PDF documents, e-mails, spreadsheets, or even "behind the scenes" formats such as XML and JSON.

View 视图获取隐藏/模型对象,并将其渲染为供最终用户查看的对象。通常情况下,这需要一个模板生成工具,为用户的web浏览器创建HTML,但很容易生成其他形式的代码,如PDF文档、电子邮件、电子表格,甚至是“幕后”格式,如XML和JSON。

Controller As suggested by its name, the controller takes user requests and routes them to the necessary model and view.

Controller 根据其名称,控制器接收用户请求并将其路由到必要的模型和视图。

CREATE A CUTELYST PROJECT

创建CUTELYST项目

Cutelyst provides a number of options in it's developer command that can be used to quickly flesh out the basic structure of your application.

Cutelyst在其开发者命令中提供了许多选项,可用于快速充实应用程序的基本结构。

If you are using QtCreator it's easier to setup the Cutelyst QtCreator assistant, and create the project there. The command line tool will be used in this tutorial as not everyone like QtCreator (I love it!).

如果您使用的是QtCreator,则更容易设置Cutelyst QtCreator助手,并在那里创建项目。命令行工具将在本教程中使用,因为不是每个人都喜欢QtCreator(我喜欢!)。

Let's create our first Cutelyst application with cutelyst command to initialize an application called Hello:

让我们使用Cutelyst命令创建第一个Cutelyst应用程序,以初始化一个名为Hello的应用程序:

$ cutelyst2 --create-app Hello
 created "Hello"
 created "Hello/src"
 created "Hello/root"
 ...

The cutelyst2 helper command will display the names of the directories and files it creates:

cutelyst2帮助命令将显示其创建的目录和文件的名称:

CMakeLists.txt        # CMake file to build application
                      # 用于构建应用程序的CMake文件
src                   # Application main code directory
                      # 应用程序主代码目录
    CMakeLists.txt    # CMake file with the settings to find your code
                      # 使用设置创建文件以查找代码
    root.cpp          # Sample Root controller implementation
                      # 根控制器实现示例
    root.h            # Sample Root controller header
                      # 根控制器头文件示例
    hello.cpp         # Base application implementation
                      # 基本应用程序实现
    hello.h           # Base application header
                      # 基本应用程序头文件
root                  # Equiv of htdocs, dir for templates, css, javascript
                      # htdocs的等价物,模板的目录,css,javascript
    static            # Directory for static files
                      # 静态文件目录

Since Cutelyst is build with C++ and so is your application, you need to first compile it. To do so make sure you run the following commands:

因为Cutelyst是用C++构建的,所以你的应用程序也是这样,你需要首先编译它。为此,请确保运行以下命令:

$ cd Hello # Get into the application root directory
           # 进入应用程序根目录
$ cd build # Get into the out of tree build directory
           # 进入树外构建目录
$ cmake .. # Prepare the project for compilation
           # 准备项目进行编译
$ make     # Compile the application
           # 编译应用程序

If everything went well and although it's too early for any significant celebration, we almost have a functioning application. We can use the cutelyst server to start the application and view the default Cutelyst page in your browser.

如果一切顺利的话,尽管现在进行任何重大庆祝活动都为时过早,但我们几乎有了一个功能正常的应用程序。我们可以使用cutelyst服务器启动应用程序,并在浏览器中查看默认的cutelyst页面。

Run the following command to start up the application web server:

运行以下命令以启动应用程序web服务器:

Note: The "-r" argument enables reloading your application when you have rebuilt your code so you don't have to stop and start the server every time you make a change and rebuild. Most of the rest of the tutorial will assume that you are using "-r" when you start the server, but feel free to manually start and stop it (use Ctrl-C to breakout of the dev server) if you prefer.

注意:“-r”参数允许在重新生成代码时重新加载应用程序,这样就不必在每次进行更改和重新生成时都停止和启动服务器。本教程剩下的大部分内容都假设在启动服务器时使用“-r”,但如果愿意,可以手动启动和停止它(使用Ctrl-C来断开开发服务器)。

Note: You can omit the application suffix .so, .dll, .dylib as it will automatically look for the file with the appropriate suffix.

注意:可以省略应用程序后缀,如.so, .dll, .dylib,因为它会自动查找带有适当后缀的文件。

$ cutelyst2 -r --server --app-file src/libHello -- --chdir ..
cutelyst.uwsgi[debug] Cutelyst loading application: /home/daniel/code/Hello/build/src/libHello.so
cutelyst.uwsgi[debug] Loaded application: "Hello"
cutelyst.dispatcher[debug] 
Loaded Private actions:
.--------------+-------+-------------.
| Private      | Class | Method      |
.--------------+-------+-------------.
| /End         | Root  | End         |
| /defaultPage | Root  | defaultPage |
| /index       | Root  | index       |
.--------------+-------+-------------.

Loaded Path actions:
.------+--------------.
| Path | Private      |
.------+--------------.
| /... | /defaultPage |
| /    | /index       |
.------+--------------.

Point your web browser to http://localhost:3000 (substituting a different hostname or IP address as appropriate) and you should be greeted by the Cutelyst welcome screen (if you get some other welcome screen or an "Index" screen, you probably forgot to specify port 3000 in your URL). Information similar to the following should be appended to the logging output of the development server:

将web浏览器指向http://localhost:3000(根据需要替换不同的主机名或IP地址),您应该会看到Cutelyst欢迎屏幕(如果您看到其他欢迎屏幕或“索引”屏幕,您可能忘记在URL中指定端口3000)。类似于以下内容的信息应附加到开发服务器的日志输出中:

cutelyst.request: "GET" request for "/" from "::1"
cutelyst.dispatcher: Path is "/"
cutelyst.stats: Response Code: 200; Content-Type: text/html; charset=utf-8; Content-Length: 20
cutelyst.stats: Request took: 0.000001s (1000000.000/s)

Note: Press Ctrl-C to break out of the development server if necessary.

注意:如有必要,按Ctrl-C退出开发服务器。

HELLO WORLD

The Simplest Way

最简单的方法

The Root.h controller is a place to put global actions that usually execute on the root URL. Open the src/Root.h and src/Root.cpp files in your editor. You will see the "index" method, which is responsible for displaying the welcome screen that you just saw in your browser.

Root.h控制器是放置通常在根URL上执行的全局操作的地方。打开src/Root.h和src/Root.cpp文件在编辑器中。您将看到“index”方法,它负责显示您刚刚在浏览器中看到的欢迎屏幕。

class Root : public Controller
{
    ...
    // Root.h
    C_ATTR(index, :Path :AutoArgs)
    void index(Context *c);
    ...
};
// Root.cpp
void Root::index(Context *c)
{
    c->response()->body() = "Welcome to Cutelyst!";
}

Later on you'll want to change that to something more reasonable, such as a "404" message or a redirect, but for now just leave it alone.

稍后,你会想将其更改为更合理的内容,例如“404”消息或重定向,但现在就别管它了。

The "c" here refers to the Cutelyst::Context, which is used to access the Cutelyst application. In addition to many other things, the Cutelyst context provides access to "response" and "request" objects. (See Cutelyst::Context, Cutelyst::Response, and Cutelyst::Request)

这里的“c”指的是用于访问Cutelyst应用程序的Cutelyst::Context。除了许多其他功能外,Cutelyst上下文还提供了对“响应”和“请求”对象的访问。(参见Cutelyst::Context、Cutelyst::Response和Cutelyst::Request)

c->response()->body() sets the HTTP response (see Cutelyst::Response) with the provided string.

c->response()->body()使用提供的字符串设置HTTP响应(请参见Cutelyst::Response)。

The :Path :AutoArgs in the C_ATTR macro are attributes which determine which URLs will be dispatched to this method.

C_ATTR宏中的:Path :AutoArgs是决定将哪些URL分派到此方法的属性。

Some MVC frameworks handle dispatching in a central place. Cutelyst, by policy, prefers to handle URL dispatching with attributes on controller methods. There is a lot of flexibility in specifying which URLs to match. This particular method will match all URLs, because it doesn't specify the path (nothing comes after "Path"), but will only accept a URL without any args because of the ":AutoArgs" attribute that will count how many QString parameters exist in the method's signature.

一些MVC框架在中心位置处理调度。根据策略,Cutelyst更喜欢使用控制器方法上的属性处理URL调度。在指定要匹配的URL时有很大的灵活性。此特定方法将匹配所有URL,因为它不指定路径(“路径”后面没有任何内容),但只接受不带任何参数的URL,因为“:AutoArgs”属性将计算方法签名中存在多少QString参数。

The default is to map URLs to controller names, it is simple to create hierarchical structures in Cutelyst by using the C_NAMESPACE macro.

默认设置是将URL映射到控制器名称,使用C_NAMESPACE宏在Cutelyst中创建层次结构很简单。

While you leave the cutelyst -r command running the application server in one window (don't forget the "-r" option!), open another window and add the following subroutine to your src/Root.h file:

在一个窗口中运行应用程序服务器的cutelyst -r命令时(不要忘记“-r”选项!),打开另一个窗口,将以下子例程添加到src/Root.h文件:

class Root : public Controller
{
    ...
    C_ATTR(hello, :Global :AutoArgs)
    void hello(Context *c) {
        c->response()->body() = "Hello, World!";
    }
    ...
};

NOTE: It's recommended to keep the implementation of the methods in the cpp file, this avoids recompiling other parts of your code that include this header, we keep it in the header here for brevity.

注意:建议将方法的实现保留在cpp文件中,这样可以避免重新编译包含此头的代码的其他部分,为了简洁起见,我们将其保留在头中。

Run make again and notice in the window running the application Server that you should get output similar to the following:

再次运行make,并在运行应用程序服务器的窗口中注意,您应该获得类似以下内容的输出:

Attempting to restart the server
...
Loaded Private actions:
.--------------+-------+-------------.
| Private      | Class | Method      |
.--------------+-------+-------------.
| /End         | Root  | End         |
| /defaultPage | Root  | defaultPage |
| /hello       | Root  | hello       |
| /index       | Root  | index       |
.--------------+-------+-------------.
...

The development server noticed the change in ...libHello.so and automatically restarted itself.

开发服务器注意到了。。。libHello.so所以自动重启。

Go to http://localhost:3000/hello to see "Hello, World!". Also notice that the newly defined 'hello' action is listed under "Loaded Private actions" in the development server debug output.

​去http://localhost:3000/hello去看"Hello, World!"。还请注意,新定义的“hello”操作列在开发服务器调试输出的“Loaded Private actions”下。

Hello, World! Using a View and a Template

Hello, World!使用视图和模板

In the Cutelyst world a "View" itself is not a page of XHTML or a template designed to present a page to a browser. Rather, it is the module that determines the type of view -- HTML, PDF, XML, etc. For the thing that generates the content of that view (such as a Grantlee template file), the actual templates go under the "root" directory.

在Cutelyst世界中,“视图”本身不是XHTML页面,也不是为向浏览器呈现页面而设计的模板。相反,它是确定视图类型的模块——HTML、PDF、XML等。对于生成该视图内容的对象(例如Grantlee模板文件),实际模板位于“root”目录下。

To create a Grantlee view, add to src/hello.cpp:

要创建Grantlee视图,请添加到src/hello.cpp:

...
#include <Cutelyst/Plugins/View/Grantlee/grantleeview.h>
...
bool Hello::init()
{
    ...
    new GrantleeView(this);
    ...
}

And link to it, src/CMakeLists.txt:

并链接到src/CMakeLists.txt:

target_link_libraries(Hello
    ...
    Cutelyst::View::Grantlee # Add this line
    ...
}

Now that the View exists, Cutelyst will be able to use it to display the view templates using the "process" method that it inherits from the Cutelyst::View class.

现在视图已经存在,Cutelyst将能够使用它来显示视图模板,使用它从Cutelyst::View类继承的“process”方法。

Grantlee is a very full-featured template facility, with excellent documentation at http://www.grantlee.org, but since this is not a Grantlee tutorial, we'll stick to only basic usage here (and explore some of the more common Grantlee features in later chapters of the tutorial).

​Grantlee是一个功能非常全面的模板工具,在http://www.grantlee.org,但由于这不是Grantle教程,我们将在这里只讨论基本用法(并在本教程后面的章节中探索一些更常见的Grantle功能)。

Create a root/hello.html template file (put it in the root under the Hello directory that is the base of your application). Here is a simple sample:

创建一个root/hello.html模板文件(将其放在应用程序基础Hello目录下的root目录中)。以下是一个简单的示例:

<p>
    This is a Grantlee view template, called '{{ template }}'.
</p>

{{ and }} are markers for the Grantlee parts of the template. Inside you can access Cutelyst variables and classes, and use Grantlee directives. In this case, we're using a special Cutelyst variable that defines the name of the template file (hello.html). The rest of the template is normal HTML.

{{和}}是模板Grantle部分的标记。在内部,您可以访问Cutelyst变量和类,并使用Grantle指令。在本例中,我们使用一个特殊的Cutelyst变量来定义模板文件(hello.html)的名称。模板的其余部分是普通的HTML。

Change the hello method in src/root.h to the following:

更改src/root.h中的hello方法。如下所示:

C_ATTR(hello, :Global)
void hello(Context *c) {
    c->setStash("template", "hello.html");
}

This time, instead of doing c->response()->body(), you are setting the value of the "template" hash key in the Cutelyst "stash", an area for putting information to share with other parts of your application. The "template" key determines which template will be displayed at the end of the request cycle. Cutelyst controllers can have an "End" action, which is called after all methods, and together with RenderView action class causes the nameless view to be rendered (unless there's a body explicitly set with c->response()->body() or a named view set with c->setView()). So your template will be magically displayed at the end of your method.

这一次,您没有执行c->response()->body(),而是在Cutelyst“stash”中设置“template”散列键的值,这是一个用于放置信息以与应用程序的其他部分共享的区域。“模板”键确定在请求周期结束时将显示哪个模板。Cutelyst控制器可以有一个“End”操作,在所有方法之后调用该操作,并与RenderView操作类一起导致呈现无名视图(除非有一个主体显式地用c->response()->body()设置,或者一个命名视图用c->setView()设置)。因此,您的模板将神奇地显示在方法的末尾。

After saving the file and issuing make, the development server should automatically restart (again, the tutorial is written to assume that you are using the "-r" option -- manually restart it if you aren't), and look at http://localhost:3000/hello in your web browser again. You should see the template that you just created.

​保存文件并发出make后,开发服务器应该自动重启(同样,编写本教程的目的是假设您正在使用“-r”选项——如果不使用,则手动重启),然后查看http://localhost:3000/hello再次在web浏览器中。您应该会看到刚刚创建的模板。

CREATE A SIMPLE CONTROLLER AND AN ACTION

创建一个简单的控制器和一个动作

Create a controller named "Site" by executing the cutelyst command:

通过执行cutelyst命令创建名为“Site”的控制器:

$ cutelyst2 --controller Site

This will create a src/site.cpp and src/site.h files. If you bring site.h up in your editor, you can see that there's not much there to see.

这将创建一个src/site.cpp和src/site.h文件。如果你把site.h放在你的编辑器中,你可以看到没有什么可看的。

We now need to register this controller (unfortunately C++/Qt's introspection has it's limitations), so in src/hello.cpp add:

我们现在需要注册这个控制器(不幸的是C++/Qt的内省有它的局限性),所以在src/hello.cpp中添加:

....
#include "site.h"
....
bool Hello::init()
{
    ....
    new Site(this);
    ....
}

In src/site.h, add the following method:

在src/site.h中添加以下方法:

C_ATTR(test, :Local)
    void test(Context *c) {
        c->stash({
                     {"username", "John"},
                     {"template", "site/test.html"}
                 });
    }

Notice the "Local" attribute on the test method. This will cause the test action (now that we have assigned an "action type" to the method it appears as a "controller action" to Cutelyst) to be executed on the "controller/method" URL, or, in this case, "site/test". We will see additional information on controller actions throughout the rest of the tutorial, but if you are curious take a look at "Actions" in Cutelyst::Action API.

注意测试方法上的“Local”属性。这将导致在“控制器/方法”URL上执行测试操作(现在我们已将“操作类型”分配给方法,它将显示为Cutelyst的“控制器操作”),或者在本例中为“站点/测试”。在本教程的其余部分中,我们将看到有关控制器操作的更多信息,但如果您有兴趣,请查看Cutelyst::Action API中的“操作”。

It's not actually necessary to set the template value as we do here. By default Grantlee will attempt to render a template that follows the naming pattern "controller/method.html", and we're following that pattern here. However, in other situations you will need to specify the template (such as if you've "forwarded" to the method, or if it doesn't follow the default naming convention).

实际上,没有必要像我们在这里所做的那样设置模板值。默认情况下,Grantle将尝试呈现一个遵循命名模式“controller/method.html”的模板,我们在这里遵循该模式。但是,在其他情况下,您需要指定模板(例如,如果您已经“转发”到该方法,或者如果它不遵循默认的命名约定)。

We've also put the variable "username" into the stash, for use in the template.

我们还将变量“username”放入了存储库中,以便在模板中使用。

Make a subdirectory "site" in the "root" directory.

在“root”目录中创建一个子目录“site”。

$ mkdir root/site

Create a new template file in that directory named root/site/test.html and include a line like:

在目录中创建一个名为root/site/test.html的新模板文件。并包含一行,如:

<p>Hello, {{ username }}!</p>

Rebuild, and once the server automatically restarts, notice in the server output that /site/test is listed in the Loaded Path actions. Go to http://localhost:3000/site/test in your browser and you should see your test.html file displayed, including the name "John" that you set in the controller.

​重新编译,一旦服务器自动重启,请注意服务器输出中的/site/test列在加载的路径操作中。去http://localhost:3000/site/test在浏览器中,您应该可以看到您的test.html文件显示,包括您在控制器中设置的名称“John”。

You can jump to the next chapter of the tutorial here: More Cutelyst Basics

​你可以在这里跳到教程的下一章:更多Cutelyst基础知识

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值