flask web api

I've been shopping around for a back end framework to support a tabletop game app, and decided to do some research to determine the best fit for my needs.

我一直在寻找支持桌面游戏应用程序的后端框架,并决定进行一些研究以确定最适合我的需求。

The objective was straightforward: to build a simple RESTful API that would allow a front end app to perform basic CRUD operations, providing me with an introduction to what the development process would look like.

目的很简单:构建一个简单的RESTful API ,使前端应用程序可以执行基本的CRUD操作,向我介绍开发过程的外观。

There are a lot of back end framework options out there, and I'm most familiar with JavaScript, C#, and Python (in that order), which limited my options somewhat.  The natural starting point was to build a simple front end that would send requests to an API, which would in turn read from and write to a local database.

有很多后端框架选项,而我最熟悉JavaScript,C#和Python(按顺序),这在某种程度上限制了我的选择。 自然的出发点是构建一个简单的前端,该前端会将请求发送到API,然后再从API读取和写入本地数据库。

I began my development process with Express, which, for reasons I'll soon explain, led me to also check out Flask and ASP.NET. I thought my findings might prove useful to others out there who are researching back end frameworks for small projects. In this article, I'll also provide code examples and the resources that I used to build everything.

我从Express开始开发过程,由于稍后将要解释的原因,它使我也检查了Flask和ASP.NET。 我认为我的发现可能对其他正在研究小型项目后端框架的人有用。 在本文中,我还将提供代码示例以及用于构建所有内容的资源。

You can access the full code on GitHub, as well.

您也可以在GitHub上访问完整代码。

I should caveat that I won't be promoting one framework over another, and haven't yet compared things like deployment, authentication, or scalability.  Your mileage may vary if those particulars are important to you!

我需要警告的是,我不会在一个框架之上推广另一个框架,并且还没有对部署,身份验证或可伸缩性之类的东西进行比较。 如果这些细节对您很重要,您的里程可能会有所不同!

I will, however, provide a TL;DR at the bottom if you just want to get the summary and key learnings.

但是,如果您只是想获得摘要和关键学习内容,我将在底部提供TL; DR

Here we go!

开始了!

定义API (Defining the API)

If you're new to web development, you might be asking, "what's an API?"

如果您不熟悉Web开发,则可能会问:“什么是API?”

I've had to ask the question a hundred times to find an answer that made sense. And it really wasn't until I built my own that I could say I understood what an API does.

我不得不问这个问题一百次才能找到一个合理的答案。 直到我自己构建了自己,我才可以说我了解API的作用

Put simply, an API, or "application programming interface", allows two different computing systems to talk to one another. In this article, I'll show a simple front end app that displays a "quest" tracker that players can view for their tabletop roleplaying game. Each quest has a "name" and a "description," both of which are displayed in the web browser.

简而言之,API或“应用程序编程接口”允许两个不同的计算系统相互通信。 在本文中,我将展示一个简单的前端应用程序,该应用程序将显示一个“任务”跟踪器,玩家可以查看其桌面角色扮演游戏。 每个任务都有一个“名称”和“描述”,两者都显示在Web浏览器中。

If I already had all of the quests listed on the website and just wanted players to view them, I would have no need for an API or back end. For this project, however, I want the ability to allow users to add quests, search for them, delete them, and so on. For those operations, I need to store the quests somewhere, but my front end app isn't able to transfer information directly to a database.

如果我已经在网站上列出了所有任务,并且只想让玩家查看它们,那么我就不需要API或后端。 但是,对于这个项目,我希望能够允许用户添加任务,搜索任务,删除任务等等。 对于这些操作,我需要将任务存储在某个地方,但是前端应用程序无法将信息直接传输到数据库。

For that, I need an API that can receive HTTP requests from the website, figure out what to do with those requests, interact with my database, and send more information back up the chain so that the user can see what happened.

为此,我需要一个API,该API可以接收来自网站的HTTP请求,弄清楚如何处理这些请求,与我的数据库进行交互,并将更多信息发送回链上,以便用户可以看到发生了什么。

The whole thing - the front end "client", the back end "API" or server, and the database - is called a "stack," or more precisely, the "full stack." For this project, I built a simple front end website as the top of the stack, and switched out everything beneath it as I tried out different frameworks and databases.

整个过程-前端“客户端”,后端“ API”或服务器以及数据库-被称为“堆栈”,或更准确地说,称为“完整堆栈”。 对于这个项目,我建立了一个简单的前端网站作为堆栈的顶部,并在尝试不同的框架和数据库时切换了其下方的所有内容。

项目结构 (Project Structure)

The structure for this project was fairly simple, with the front end client separated from three different servers that I would spin up as necessary to serve the API.

该项目的结构非常简单,前端客户端与三台不同的服务器分开,我将根据需要旋转以提供API。

I used Visual Studio Community as my code editor and IDE, with the requisite language packages installed for JavaScript, Python, and C#.

我将Visual Studio社区用作代码编辑器和IDE,并为JavaScript,Python和C#安装了必需的语言包。

I'll provide an overview of my experience with each framework in turn, with links to the tutorials and packages that I used to get them to work with the client. But first, let's take a look at the front end!

我将依次介绍我对每个框架的经验,并提供指向教程和软件包的链接,这些教程和软件包用于使它们与客户端一起使用。 但首先,让我们看一下前端!

客户端:Vue.js (The Client: Vue.js)

The goal for the client was to have a simple website that would receive information from the database through the API and display it to the user. To streamline the process, my requirements were that the client would only need to "read" all of the items in the database, and provide the user with the ability to "create" a new quest.

客户的目标是拥有一个简单的网站,该网站将通过API从数据库接收信息并将其显示给用户。 为了简化流程,我的要求是客户只需要“读取”数据库中的所有项目,并为用户提供“创建”新任务的能力。

These "read" and "create" operations - the "R" and "C" in "CRUD" - are analogous to the HTTP methods of "GET" and "POST," which we'll see in the code below.

这些“读取”和“创建”操作(“ CRUD”中的“ R”和“ C”)类似于“ GET”和“ POST”的HTTP方法,我们将在下面的代码中看到它们。

In front end development, I'm most comfortable using Vue, and used the Vue CLI to scaffold a basic client, with the following file structure:

在前端开发中,我最喜欢使用Vue ,并使用Vue CLI搭建具有以下文件结构的基本客户端:

I replaced the boilerplate markup provided by the Vue CLI with the following:

我将Vue CLI提供的样板标记替换为以下内容:

<template><div id="app"><h1>RPG Quests</h1><p v-for="(quest, index) in quests" v-bind:key="index">{{quest.name}}: {{quest.description}}</p><input type="text" v-model="newQuestName" placeholder="Quest Name" /> <br /><input type="text" v-model="newQuestDescription" placeholder="Quest Description" /><br /><br /><button v-on:click="postQuest">Add Quest</button></div>
</template>

And the corresponding Vue code:

以及相应的Vue代码:

import axios from 'axios';export default {name: 'App',data: function () {return {quests: null,newQuestName: null,newQuestDescription: null}},methods: {getQuests: function () {axios.get('http://localhost:3000/quests').then(response => (this.quests = response.data));},addQuest: function () {axios.post('http://localhost:3000/quests', {name: this.newQuestName,description: this.newQuestDescription});},postQuest: function () {axios.all([this.addQuest(), this.getQuests()]);this.$forceUpdate();}},mounted: function () {this.getQuests();}}

If you're not familiar with Vue, the specifics of the front end aren't that important! Of significance here is that I'm using a JavaScript package called Axios to make my GET and POST requests to a potential server.

如果您不熟悉Vue,则前端的细节并不那么重要! 这里重要的是,我正在使用一个名为AxiosJavaScript程序包向潜在的服务器发出GET和POST请求。

When the client loads, it'll make a GET request to the URL http://localhost:3000/quests to load all quests from the database. It also provides a couple of input fields and a button that will POST a new quest.

客户端加载后,它将向URL http:// localhost:3000 / quests发出GET请求,以从数据库加载所有任务。 它还提供了几个输入字段和一个将发布新任务的按钮。

Using the Vue CLI to serve the client on http://localhost:8080, the front end of the app looks like this in action:

使用Vue CLI在http:// localhost:8080上为客户端提供服务,应用程序的前端看起来像这样:

Once quests are added to the database, they'll start appearing in between the "RPG Quests" header and the input fields.

将任务添加到数据库后,它们将开始出现在“ RPG Quests”标题和输入字段之间。

客户资源 (Client Resources)

To build the client, I used:

为了构建客户端,我使用了:

  • NodeJS/NPM for package management

    NodeJS / NPM的软件包管理

  • Vue CLI for scaffolding, serving, and building projects

    Vue CLI,用于脚手架,服务和建筑项目

  • Axios for making HTTP requests to the API

    Axios,用于向API发出HTTP请求

  • Vue Axios Documentation for making sense of how to use Axios in concert with the API

    Vue Axios文档 ,了解如何与API配合使用Axios

  • Postman for testing API requests through the browser before implementing them in the client.

    邮递员,用于在客户端中实现API请求之前通过浏览器测试API请求。

JavaScript API:Express (JavaScript API: Express)

Express is a lightweight web framework for NodeJS that allows you to write server-side applications with JavaScript.

Express是NodeJS的轻量级Web框架,允许您使用JavaScript编写服务器端应用程序。

It's un-opinionated, which means that you can build your applications how you like without it defining the architecture for you. You can add packages to improve functionality as you fancy, which I found to be a double-edged sword as a newbie to the framework. More on that later.

它是不受限制的,这意味着您可以按自己的喜好构建应用程序,而无需为您定义体系结构。 您可以根据需要添加软件包以改善功能,我发现它是框架的新手,是一把双刃剑。 以后再说。

Being most comfortable in JavaScript, I was excited by the prospect of having the entire stack run on just one language instead of several. I had heard of the "MEVN Stack," which denotes a full stack application that is comprised of MongoDB, Express, Vue, and NodeJS, and decided to try that out for this iteration of the project.

最熟悉JavaScript的时候,我很高兴看到整个堆栈仅以一种语言而不是几种语言运行。 我听说过“ MEVN堆栈”,它表示由MongoDB ,Express,Vue和NodeJS组成的完整堆栈应用程序,因此决定尝试此项目的迭代。

I followed a web API tutorial to first build a template app, then used another MEVN tutorial to fill in the details of how to get the API to communicate with the Vue client that I had built. The Express API that I created for this project follows a similar structure to the former, using MongoDB as the database:

我遵循了Web API教程 ,首先构建了模板应用程序,然后使用了另一个MEVN教程来填写有关如何使API与所构建的Vue客户端进行通信的详细信息。 我为此项目创建的Express API采用与前一个类似的结构,使用MongoDB作为数据库:

If you're coming from a JavaScript background, Express is fairly easy to read, even if you're not familiar with some of the back end terminology. The following is a snippet from /routes/quests.js, for example, which handles the HTTP endpoint requests:

如果您来自JavaScript背景,即使您不熟悉某些后端术语,Express也非常易于阅读。 例如,以下是/routes/quests.js的片段,用于处理HTTP 端点请求:

router.get('/', async (req, res) => {try {const quests = await Quest.find();res.json(quests);} catch (err) {res.status(500).json({ message: err.message });}
});router.post('/', async (req, res) => {const quest = new Quest({name: req.body.name,description: req.body.description});try {const newQuest = await quest.save();res.status(201).json(newQuest);} catch (err) {res.status(400).json({ message: err.message });}
});

The general theme of the code is to receive a request, attempt to contact the database to do work, and then send a response back to whoever's asking. The specifics can be quite complex, particularly if you're writing your own middleware that does things in between the request and response, but the code is at least readable.

该代码的一般主题是接收请求,尝试联系数据库以进行工作,然后将响应发送回给任何询问的人。 具体细节可能非常复杂,特别是如果您正在编写自己的中间件 ,该中间件在请求和响应之间执行操作,但是代码至少可读性强。

I found MongoDB to be painless to work with as a NoSQL database.  If you're working with Express, you'll most likely use Mongoose as an ODM - basically like a "middle person" that translates a model of what your data looks like to the database.

我发现MongoDB可以轻松地用作NoSQL数据库。 如果您使用Express,最有可能将Mongoose用作ODM-基本上就像一个“中间人”,它将数据的外观模型转换为数据库。

The model in this app (called a "schema" in Mongoose terms) is really simple, located in /models/quests.js:

该应用程序中的模型(用猫鼬称呼为“模式”)非常简单,位于/models/quests.js中:

const questSchema = new mongoose.Schema({name: {type: String,required: true},description: {type: String,required: true}
});

The above indicates that the database should store our two fields: a quest name and a quest description.  Both of these fields are strings, and required. All GET and POST requests will have to conform to this model to interact with the database.

上面指出数据库应该存储我们的两个字段:任务名称和任务描述。 这两个字段都是字符串,并且是必填字段。 所有GET和POST请求都必须符合此模型才能与数据库进行交互。

After wiring all of this up and POSTing a few new quests, the front end site started populating with data:

在完成所有这些工作并发布一些新任务之后,前端站点开始填充数据:

The process of setting up the Express API was not without its hair pulling, however. Being a primarily front end and 2D game developer, I've become intimately familiar with how dispersed the JavaScript ecosystem can feel. This frustration was magnified in attempting to build a back end app. There are a lot of packages required to get everything up and running, each of which having its own required configuration and implementation.

但是,设置Express API的过程并非一帆风顺。 作为主要的前端和2D游戏开发人员,我已经非常熟悉JavaScript生态系统的分散感。 在尝试构建后端应用程序时,这种挫败感被放大了。 要使一切正常运行,需要很多软件包,每个软件包都有其自己所需的配置和实现。

If you're looking for a framework that just does everything out of the box, Express is most certainly not the choice for you. It's lightweight, flexible, and easy to read, in a very "choose-your-own-adventure" fashion. I quite like how clean the code is and the ability to structure my projects as I see fit, but troubleshooting and error handling do leave a lot to be desired.

如果您正在寻找一个可以立即完成所有工作的框架,那么Express绝对不是您的选择。 它轻巧,灵活且易于阅读,非常“选择自己的冒险”方式。 我非常喜欢代码的简洁程度和能够按我认为合适的方式构建项目的能力,但是故障排除和错误处理确实有很多不足之处。

JavaScript / Express资源 (JavaScript/Express Resources)

To build the JavaScript API, I used:

为了构建JavaScript API,我使用了:

  • NodeJS/NPM for package management

    NodeJS / NPM的软件包管理

  • Express as the main web framework

    Express作为主要的Web框架

  • Dotenv to create environment-specific variables

    Dotenv创建特定于环境的变量

  • Nodemon to watch files for changes and restart the server so I didn't have to

    Nodemon可以监视文件中的更改并重新启动服务器,因此我不必

  • CORS to allow for cross-origin requests (basically a pain if you're trying to make requests from a client to a server that are both running locally on your machine)

    CORS允许跨域请求 (如果您尝试从客户端向服务器发出都在计算机上本地运行的请求,这通常会很麻烦)

  • MongoDB for the NoSQL database

    MongoDB用于NoSQL数据库

  • Mongoose for writing models that map onto MongoDB

    Mongoose用于编写映射到MongoDB的模型

  • This API tutorial to provide a basic understanding of how to create an Express-MongoDB stack

    该API教程提供了有关如何创建Express-MongoDB堆栈的基本知识

  • This MEVN tutorial to fill in the gaps of running a MongoDB-Express-Vue-Node full stack

    这份MEVN教程填补了运行MongoDB-Express-Vue-Node全栈的空白

Python API:烧瓶 (Python API: Flask)

In the process of building the Express API, I had a conversation with a data science friend who works in Python. This gave me the idea of trying out non-JavaScript frameworks to see if they were better suited for my app.

在构建Express API的过程中,我与使用Python的数据科学朋友进行了交谈。 这给了我尝试非JavaScript框架以查看它们是否更适合我的应用程序的想法。

I took a cursory look at Django, since I'd been hearing about it as a powerhouse back end framework that provides everything out of the box. I was a little intimidated by how opinionated it seemed, and opted to try out Flask instead, which kind of felt like the Python equivalent of Express.

我粗略地看了一下Django ,因为我一直听说它是一个强大的后端框架,它提供了所有现成的功能。 我对它的自以为是的感觉有些害怕,因此选择尝试Flask ,感觉就像是Express的Python。

I followed the first few bits of the excellent Flask Mega-Tutorial to get my app structure set up, using the companion RESTful API tutorial to fill in the pieces of HTTP requests. The file structure turned out to be only a shade more complex than that of the Express API:

我遵循了出色的Flask Mega-Tutorial的前几部分,使用配套的RESTful API教程来填充HTTP请求片段,以设置我的应用程序结构。 事实证明,文件结构只比Express API复杂一点:

The tutorial I followed uses SQLite for its database, with Flask-SQLAlchemy as an ORM. The HTTP request code that's most analogous to the Express API is located in /app/routes.py:

我遵循的教程将SQLite用于其数据库,并使用Flask-SQLAlchemy作为ORM 。 最类似于Express API的HTTP请求代码位于/app/routes.py中:

@app.route('/quests', methods=['GET'])
def get_quests():questQuery = Quest.query.all()quests = {}for quest in questQuery:quests[quest.name] = quest.descriptionreturn jsonify(quests)@app.route('/quests', methods=['POST'])
def post_quest():newQuest = Quest(name=request.json['name'], description=request.json['description'])db.session.add(newQuest)db.session.commit()return "Quest Added!"

Similarly, the database model (akin to the Mongoose "schema") is in /app/models.py:

同样,数据库模型(类似于Mongoose的“模式”)位于/app/models.py中:

class Quest(db.Model):name = db.Column(db.String(256), primary_key=True, index=True, unique=True)description = db.Column(db.String(256), index=True, unique=True)

As I mentioned, I'm more familiar with JavaScript and C# than with Python, and working with the latter to build the Flask API felt like cheating. Certain things like pathing, package handling, and writing workable code were just easy, although I did get hung up on getting the API to correctly parse JSON for the client. I suspect that was more of an issue of my unfamiliarity with the language than anything else, but it did take time to troubleshoot.

如前所述,我对JavaScript和C#的了解要比对Python更为熟悉,与Python一起构建Flask API感觉就像是在作弊。 路径,包处理和编写可行的代码之类的某些事情都很容易 ,尽管我确实迷上了让API正确解析客户端JSON的想法。 我怀疑这更多是我对语言不熟悉的问题,但确实需要花费一些时间进行故障排除。

To be quite honest, coming from a non-Flask background, I did kind of expect to complete a couple of tutorials and spin up an API without having to do all that much work for it.

老实说,我来自非Flask的背景,我确实希望完成一些教程并启动一个API,而不必为此做很多工作。

I can't say that it turned out that way, as Python does have its own particulars that require some time to get used to. Still, the Python ecosystem appears to be extremely well organized, and I enjoyed my time building the Flask API.

我不能说事实就是这样,因为Python确实有其自身的特点,需要一些时间来习惯。 不过,Python生态系统似乎组织得非常好,我很喜欢构建Flask API。

I've also heard that Django is a better and more scalable option for larger projects. But it seems like it would involve a separate, and steeper, learning curve to become proficient.

我还听说Django对于大型项目是一个更好,更可扩展的选择。 但这似乎需要一条单独的,更陡峭的学习曲线才能熟练。

Flask was easy enough for me as a non-Python developer to pick up and build something over a weekend. I suspect that learning Django would take quite a bit longer, but with potentially greater dividends over the long run.

作为一个非Python开发人员,Flask对我来说足够容易,可以在一个周末内完成并构建一些东西。 我怀疑学习Django会花费更长的时间,但从长远来看可能会带来更大的收益。

Python /烧瓶资源 (Python/Flask Resources)

To build the Flask API, I used:

为了构建Flask API,我使用了:

  • Python 3/pip for package management

    Python 3 / pip进行软件包管理

  • Flask as the main web framework

    Flask作为主要的Web框架

  • python-dotenv to configure environment variables

    python-dotenv配置环境变量

  • SQLite as the database

    SQLite作为数据库

  • Flask-SQLAlchemy as the ORM to work with SQLite

    Flask-SQLAlchemy作为与SQLite一起使用的ORM

  • Flask-Migrate as an additional tool to migrate data to SQLite

    Flask-Migrate作为将数据迁移到SQLite的附加工具

  • Flask-CORS to handle the same CORS issue as with the Express API

    Flask-CORS处理与Express API相同的CORS问题

  • The Flask Mega-Tutorial to learn the basics

    Flask Mega教程 ,学习基础知识

  • The Flask REST API tutorial to understand how to receive HTTP requests

    Flask REST API教程 ,了解如何接收HTTP请求

C API:ASP.NET (C API: ASP.NET)

I can't tell you how many times I've Googled ".NET" to understand what it is, how it's different from ASP.NET, and why I'd want to use any of it. My C# knowledge comes mainly from working with Unity, which exists somewhat adjacent to .NET and doesn't provide for a lot of exposure to Microsoft's larger ecosystem.

我无法告诉您使用Google .NET多少次才能了解它的含义,它与ASP.NET的不同之处以及我为什么要使用其中任何一个。 我的C#知识主要来自与Unity的合作, Unity在某种程度上与.NET相邻,并且无法充分了解Microsoft的更大生态系统。

I've spent some time researching Razor Pages and MVC, and finally came to understand ASP.NET's breadth of features as Microsoft's open source web framework. I decided to toss ASP.NET into the hat for a potential back end for my app, and set about working through the official web API tutorial with ASP.NET Core and MongoDB.

我花了一些时间研究Razor Pages和MVC ,最终了解了ASP.NET作为Microsoft的开源Web框架的广泛功能。 我决定将ASP.NET丢给我的应用程序的潜在后端,然后着手通过ASP.NET Core和MongoDB来研究官方Web API教程 。

The file structure for this version of the API was more complex than the others, given that .NET projects tend to have a much larger footprint:

鉴于.NET项目通常具有更大的占用空间,因此该版本的API的文件结构比其他版本更复杂。

I should also mention that I already had Visual Studio and all of the required workloads installed, which made the setup process easier. Plus, having spent time with MongoDB for the Express API, I found the database portion of the project to be similar, although by default, ASP.NET seems to prefer using Microsoft's SQL Server and the Entity Framework ORM.

我还应该提到我已经安装了Visual Studio和所有必需的工作负载,这使安装过程更加容易。 另外,在MongoDB上花了很多时间处理Express API之后,我发现该项目的数据库部分是相似的,尽管默认情况下,ASP.NET似乎更喜欢使用Microsoft的SQL Server和Entity Framework ORM 。

The ASP.NET code for HTTP requests is a bit more complex than what we've seen with the two other APIs, but it's no match for all of the code that sits around it.

HTTP请求的ASP.NET代码比其他两个API复杂,但与周围的所有代码都不匹配。

First, consider this snippet in /Controllers/QuestController.cs that handles requests:

首先,考虑/Controllers/QuestController.cs中处理请求的代码段:

namespace QuestAPI.Controllers
{[Route("quests/")][ApiController]public class QuestsController : ControllerBase{private readonly QuestService _questService;public QuestsController(QuestService questService){_questService = questService;}[HttpGet]public ActionResult<List<Quest>> Get() =>_questService.Get();[HttpPost]public ActionResult<Quest> Create(Quest quest){_questService.Create(quest);return CreatedAtRoute("GetQuest", new { id = quest.Id.ToString() }, quest);}}
}

Not too terrible, almost kind of readable, in a C# sort of way. The data model in /Models/Quest.cs is even easier:

用C#的方式不太可怕,几乎可以理解。 /Models/Quest.cs中的数据模型更加简单:

namespace QuestAPI.Models{public class Quest{[BsonId][BsonRepresentation(BsonType.ObjectId)]public string Id { get; set; }[BsonElement("Name")]public string Name { get; set; }public string Description { get; set; }}
}

These two snippets essentially do the same things as the previous examples that we've seen: take requests from the front end, process them to get or modify data in the database, and send a response back to the client.

这两个片段与我们之前看到的示例实质上具有相同的作用:从前端获取请求,处理它们以获取或修改数据库中的数据,然后将响应发送回客户端。

Yet, as you can probably tell from the complex file structure, there's so much code that surrounds these snippets, along with Interfaces, Dependency Injection, and other abstractions, that it can be challenging to understand how it all works together.

但是,正如您可能从复杂的文件结构中看到的那样,这些代码片段以及接口 , 依赖注入和其他抽象周围有太多代码,因此了解它们如何协同工作可能具有挑战性。

Consider the following configuration code in /Startup.cs:

考虑/Startup.cs中的以下配置代码:

public void ConfigureServices(IServiceCollection services){services.Configure<QuestDatabaseSettings>(Configuration.GetSection(nameof(QuestDatabaseSettings)));services.AddSingleton<IQuestDatabaseSettings>(sp => sp.GetRequiredService<IOptions<QuestDatabaseSettings>>().Value);services.AddSingleton<QuestService>();services.AddCors(options =>{options.AddPolicy(MyAllowSpecificOrigins, builder =>{builder.WithOrigins("http://localhost:3000/quests", "http://localhost:8080").AllowAnyHeader().AllowAnyMethod();});});services.AddControllers();}

Or this particularly nested bit from a separate SQL Server web API tutorial:

或者,这是来自单独的SQL Server Web API教程的特别嵌套部分:

[HttpGet]public async Task<ActionResult<IEnumerable<TodoItemDTO>>> GetTodoItems(){return await _context.TodoItems.Select(x => ItemToDTO(x)).ToListAsync();}

Lol. What?? As a new user, even familiar as I am with C#, I can go line-by-line to understand each abstraction, or I can just trust that the framework is handling everything for me and forget about it.

大声笑。 什么?? 作为一个新用户,即使像我对C#一样熟悉,我也可以逐行了解每种抽象,或者我可以相信该框架正在为我处理所有事情,而无需理会。

I tend to want to know exactly how my code works so that I can fix or alter it if necessary. But I certainly feel like my time spent learning the ins-and-outs of ASP.NET could be better utilized towards mastering another framework.

我倾向于想确切地了解我的代码如何工作,以便在必要时可以对其进行修复或更改。 但是我当然觉得我花时间学习ASP.NET的内容可以更好地用于掌握另一个框架。

To be fair, ASP.NET appears to be similar to Django in being more opinionated and providing you with a ton of stuff out of the box, including an authentication solution, database management, and the lot. If these things are important to you, it's certainly worth considering.

公平地讲,ASP.NET看起来与Django类似,但更自以为是,为您提供了很多现成的东西,包括身份验证解决方案,数据库管理和其他功能。 如果这些事情对您很重要,那么绝对值得考虑。

It also has the full support of Microsoft and an open source community. So if you're looking at developing enterprise-level applications that need to scale, you might want to take a longer look at ASP.NET as a potential solution.

它还具有Microsoft和开放源代码社区的全面支持。 因此,如果您正在考虑开发需要扩展的企业级应用程序,则可能需要更深入地研究ASP.NET作为潜在的解决方案。

C / ASP.Net资源 (C/ASP.Net Resources)

To build the ASP.Net API, I used the following resources:

为了构建ASP.Net API,我使用了以下资源:

  • Visual Studio Community as my code editor and IDE, with the ASP.NET and web development workload installed (I already had MongoDB running from the Express API)

    Visual Studio Community作为我的代码编辑器和IDE,安装了ASP.NET和Web开发工作负载(我已经从Express API运行过MongoDB)

  • Microsoft's official tutorial for building web APIs with ASP.NET and MongoDB

    Microsoft的使用ASP.NET和MongoDB构建Web API的官方教程

TL; DR (TL;DR)

In all, with some slight variations and hiccups among them, I've gotten each of the web APIs to work with the Vue client, with the ability to view quests from and add quests to the database. Hopefully, my explanation of the process has been helpful in your own search for a back end framework, but here are some additional recommendations just in case:

总而言之,尽管其中有一些细微的变化和小问题,但我已经使每个Web API都能与Vue客户端一起使用,并且能够查看来自数据库的任务并将任务添加到数据库中。 希望我对过程的解释对您自己寻找后端框架有帮助,但是为了以防万一,这里有一些其他建议:

  • If you're a JavaScript developer and/or want to manage everything that your application does, including its architecture, consider using Express.如果您是JavaScript开发人员和/或想要管理应用程序所做的所有事情,包括其体系结构,请考虑使用Express。
  • If you're a Python developer and/or want a pleasant experience in developing small projects, try Flask, but consider using Django if you need more out-of-the-box support and don't mind conforming to an opinionated framework.如果您是Python开发人员和/或想要在开发小型项目中获得愉快的经验,请尝试Flask,但是如果您需要更多的现成支持并且不介意遵循自以为是的框架,请考虑使用Django。
  • If you're a C# developer and willing to spend the time to learn the most arcane details of C# coding best practices, consider using ASP.NET. Alternatively, if you need enterprise-level support right out of the box, you'd be hard-pressed to find better.如果您是C#开发人员,并且愿意花时间学习C#编码最佳实践的最神秘的细节,请考虑使用ASP.NET。 另外,如果您需要开箱即用的企业级支持,则很难找到更好的解决方案。
  • If you don't know what to use and just want to learn back end development, take a look at Flask.  It's easy to work with and will teach you the basics that you'll need to know for building web apps in any coding language.如果您不知道使用什么,而只想学习后端开发,请看一下Flask。 它易于使用,并会教您使用任何编码语言构建Web应用程序所需的基本知识。
  • If you don't know what to use and want an adventure, choose Express. There's a rabbit hole of package management and Stack Overflow questions waiting that may make you tear your hair out, but you'll learn a lot about the JavaScript ecosystem and web development in general.如果您不知道该使用什么并且想要冒险,请选择“快递”。 包管理和Stack Overflow问题的待命之处可能会让您大吃一惊,但是通常您会学到很多关于JavaScript生态系统和Web开发的知识。

Additionally, two things bear mentioning that threw me for a spin in this process: CORS and environment variables. The former I've mentioned in this article a couple of times already, but it's worth discussing again to understand the scope of building a full stack app on your machine.

此外,还有两件事需要提及,这使我在此过程中感到困惑:CORS和环境变量。 我已经在本文中提到过两次,但是值得再次讨论以了解在计算机上构建全栈应用程序的范围。

Unless you have an integrated development environment that's handling the whole stack for you, you'll likely have a client, a server, and a database that are all running independently of one another.

除非您拥有一个集成的开发环境来为您处理整个堆栈,否则您可能会有一个客户端,服务器和一个数据库,它们彼此独立运行。

In the Express API section above, for example, I was running

例如,在上面的Express API部分中,我正在运行

  1. the Vue CLI server, which rendered my front end app on port 8080; Vue CLI服务器,该服务器在8080端口上渲染了我的前端应用程序;
  2. an NPM script to spin up the Express API server on port 3000; andNPM脚本启动端口3000上的Express API服务器; 和
  3. a separate instance of the Mongo database to get everything working together. That's three command prompts open and a general mess!一个单独的Mongo数据库实例,以使所有内容协同工作。 那是三个打开的​​命令提示符和一个普遍的混乱!

If you dig into the Vue code above (or on GitHub), you'll see that the requests made on behalf of the client, running on http://localhost:8080, are to the server on http://localhost:3000, which is where the Express API is listening. This is called "cross-origin resource sharing," or CORS, and it's blocked by the browser for security concerns. Most frameworks require you to install an additional package to get the whole thing running in your local environment.

如果您深入研究以上(或在GitHub上)的Vue代码,您会发现代表客户端(运行在http:// localhost:8080上)发出的请求将发送到http:// localhost:3000上的服务器,这是Express API监听的地方。 这称为“跨域资源共享”或CORS ,出于安全方面的考虑,浏览器已将其阻止。 大多数框架要求您安装其他软件包,以使整个组件在本地环境中运行。

Second, you'll want to become comfortable with environment variables, which can really help smooth some rough pathing edges at runtime. I used dotenv and Flask-Env for the Express and Flask projects, respectively.

其次,您将需要适应环境变量 ,这确实可以帮助在运行时平滑某些粗糙的路径边缘。 我分别在Express和Flask项目中使用了dotenv和Flask-Env 。

Both packages allow you to configure things like where your database lives, or what default port your application should be using, in one document. Your application then uses that document at runtime to figure out where to find everything, without any further configuration needed from you.

这两个软件包都允许您在一个文档中配置数据库的位置或应用程序应使用的默认端口等内容。 然后,您的应用程序将在运行时使用该文档来找出在哪里可以找到所有内容,而无需您进行任何进一步的配置。

One final note that may be helpful if you're just working on a back end project and don't want to go through the trouble of building a front end client: consider using a third-party app like Postman. I used it to make HTTP requests to each of the APIs to make sure they were working properly before layering on the Vue client and trying to get the whole stack running altogether.

最后一点可能对您有所帮助,如果您只是在从事后端项目,而又不想麻烦建立前端客户端的话:请考虑使用Postman之类的第三方应用程序。 我使用它向每个API发出HTTP请求,以确保它们在Vue客户端上分层并尝试使整个堆栈完全运行之前能够正常工作。

I hope this article has been helpful for you in your own process of looking for a back end framework.  Let me know what you find!

希望本文对您寻找后端框架的过程有所帮助。 让我知道你发现了什么!

If you enjoyed this article, please consider checking out my games and books, subscribing to my YouTube channel, or joining the Entromancy Discord.

如果您喜欢这篇文章,请考虑查看我的游戏和书籍 , 订阅我的YouTube频道或加入Entromancy Discord 。

M. S. Farzan, Ph.D. has written and worked for high-profile video game companies and editorial websites such as Electronic Arts, Perfect World Entertainment, Modus Games, and MMORPG.com, and has served as the Community Manager for games like Dungeons & Dragons Neverwinter and Mass Effect: Andromeda. He is the Creative Director and Lead Game Designer of Entromancy: A Cyberpunk Fantasy RPG and author of The Nightpath Trilogy. Find M. S. Farzan on Twitter @sominator.

法赞(MS Farzan)博士 他曾为知名的视频游戏公司和编辑网站(例如,Electronic Arts,Perfect World Entertainment,Modus Games和MMORPG.com)撰写和工作,并曾担任《龙与地下城:龙骨无双》和《 质量效应:仙女座》等游戏的社区经理。 。 他是《 Entronancy:Cyber​​punk Fantasy RPG》的创意总监和首席游戏设计师,并且是《 The Nightpath Trilogy》的作者。 在Twitter @sominator上找到MS Farzan 。

翻译自: https://www.freecodecamp.org/news/i-built-a-web-api-with-express-flask-aspnet/

flask web api

flask web api_我使用Express,Flask和ASP.NET重建了相同的Web API。 这是我发现的。相关推荐

  1. ASP.NET Core Web Razor Pages系列教程:使用ASP.NET Core创建Razor Pages Web应用程序

    ASP .Net Core Razor Pages MySQL Tutorial 本系列教程翻译自微软官方教程,官方教程地址:Tutorial: Create a Razor Pages web ap ...

  2. ASP.NET 4.0尚未在 Web 服务器上注册 解决方法

    使用VS2010创建web应用程序时出现如下提示ASP.NET 4.0尚未在 Web 服务器上注册.为了使网站正确运行,可能需要手动将 Web 服务器配置为使用 ASP.NET 4.0,按 F1 可了 ...

  3. [Link]选择一个 Python Web 框架:Django vs Flask vs Pyramid

    选择一个 Python Web 框架:Django vs Flask vs Pyramid

  4. Flask后端实践 连载十六 Flask实现微信Web端及APP端登录注册

    Flask后端实践 连载十六 Flask实现微信Web端及APP端登录注册 tips: 本文将实现微信Web端和APP端登陆注册 本文基于python3编写 代码仓库 项目场景 某天,项目经理说,项目 ...

  5. flask web如何加载html,Flask Web开发学习笔记(三)

    本文主要整理下几个Flask扩展: 0.Flask-Bootstrap:集成Twitter开发的一个开源框架Bootstrap. 1.Flask-Script:为Flask程序添加一个命令行解析器 2 ...

  6. YOLOv5/v7 Flask Web 监测平台 | YOLOv5/v7 Flask Web 部署

    YOLOv7 Flask Web 监测平台图片效果展示 YOLOv7 Flask Web 监测平台视频效果展示 YOLOv7 Flask Web 检测平台 什么是Flask? 简介 Flask是一个轻 ...

  7. flask websocket json_Win10环境下使用Flask配合Celery异步推送实时/定时消息/2020年最新攻略...

    原文转载自「刘悦的技术博客」https://v3u.cn/a_id_163 首先得明确一点,和Django一样,在2020年Flask 1.1.1以后的版本都不需要所谓的三方库支持,即Flask-Ce ...

  8. Flask框架的第一个“Hello Flask”

    Flask简介 flask是一款非常流行的Python Web框架,出生于2010年,作者是Armin Ronacher,本来这个项目只是作者在愚人节的一个玩笑,后来由于非常受欢迎,进而成为一个正式的 ...

  9. Flask后端实践 连载十八 Flask输出PDF报表

    Flask后端实践 连载十八 Flask输出PDF报表 tips: 简单实现Flask输出PDF报表 本文基于python3编写 代码仓库 项目场景 由于项目是工程上的使用,不仅需要对采集的数据进行分 ...

最新文章

  1. FreeBSD中3D加速功能的启用
  2. 如何更改自己电脑上的COM端口号
  3. Gearman 异步处理委派任务
  4. 学习underscore源码整体架构,打造属于自己的函数式编程类库
  5. javascript的BOM
  6. java表格怎么添加按钮_1.6.2 在表格中添加按钮
  7. JSP — GET 与 POST 的区别
  8. 数据结构实验4-栈与字符串
  9. id门禁卡复制到手机_手机NFC也可以刷ID卡门禁?无聊测试居然成功了!
  10. greensock下载_GreenSock面向初学者:Web动画教程(第1部分)
  11. 如何在网页打开CAD,DWG文件,(在线CAD)在线CAD平台,H5前端显示CAD,网页CAD
  12. eclipse如何修改项目的jdr或jre版本
  13. 汇编语言之DOSBox
  14. SOLIDWORKS参数化设计方式几多种,你都用恰当了吗?
  15. 《辛雷学习方法》读书笔记——第三章 身体
  16. 华为HCIE RS笔记-20 OSPF的V-Link
  17. el-upload 模拟点击
  18. 关于pom.xml一直提示Could not transfer artifact(无法搬运)+无法解析maven依赖(更新)的问题,我在学习springboot的过程中遇到的一些问题(持续更新中)
  19. [Ynoi2015]纵使日薄西山
  20. DNA存储技术—让信息保存万年

热门文章

  1. Raft算法(zookeeper核心算法)
  2. 在苹果Mac上的“日历”中怎样使用Siri建议?
  3. pandas :案例详解 loc函数、iloc函数 数据切片
  4. Airbnb个性化推荐
  5. 关于中国人工智能的三大隐患
  6. spring boot + maven + opencv 车牌识别系统,包含车牌检测、车牌号识别训练
  7. 爬虫:ip地址查询代码
  8. S12. 中介者模式
  9. Ubuntu18.04美化成Mac桌面
  10. Android手机应用开发(八) | 制作简单音乐播放器