Как я могу удалить Flask?
Я пытаюсь удалить Flask с моего Mac, но получаю следующую ошибку:
вы пробовали с пипсом? — Udy
это зависит от того, как вы установили Flask — Leonardo.Z
3 ответы
-
Если вы установили колбу с pip , Используйте pip uninstall flask .
Если вы не знаете, как вы установили flask, но не использовали pip, попробуйте выполнить эту команду:
python -c «import os, flask; print(os.path.dirname(flask.__file__))»
Затем вручную удалите весь этот каталог из файловой системы.
ответ дан 16 окт ’14, 04:10
я действительно делал sudo pip install Flask , но через некоторое время, sudo pip uninstall Flask В результате Не могу удалить «Фласк». Файлов для удаления не найдено. (В вашем первом ответе отсутствует буква «n».) Но на помощь пришел ваш второй ответ грубой силы. — Майкл Шепер
Инсталляция¶
Flask зависит от некоторых внешних библиотек — таких, как Werkzeug и Jinja2. Werkzeug — это инструментарий для WSGI — стандартного интерфейса Python между веб-приложениями и различными серверами, предназначен как для разработки, так и развёртывания. Jinja2 занимается отображением шаблонов.
Итак, как же быстро получить всё необходимое на ваш компьютер? Есть много способов, которыми вы это можете проделать, но самый обалденный — это virtualenv, так что давайте глянем в первую очередь на него.
Для начала вам понадобится Python 2.6 или новее, так что убедитесь, что у вас инсталлирован свежий Python 2.x. При использовании Flask с Python 3 загляните в раздел python3-support .
virtualenv¶
Возможно, Virtualenv — именно то, что вы захотите использовать при разработке, а если у вас на рабочем сервере есть доступ к командной оболочке, вероятно, вы захотите использовать Virtualenv и здесь.
Какую из проблем решает virtualenv? Если вам нравится Python так, как он нравится мне, скорее всего, вы захотите использовать его и в других проектах — вне приложений, созданных на базе Flask.
Но чем больше у вас проектов, тем больше вероятность, что вы будете работать с разными версиями самого Python, или, по крайней мере, с различными версиями библиотек Python. Посмотрим правде в глаза: довольно часто библиотеки нарушают обратную совместимость, и маловероятно, что серьёзное приложение будет работать вообще без каких-либо зависимостей. Так что же делать, если два или более из ваших проектов имеют конфликтующие зависимости?
Наше спасение — Virtualenv! Virtualenv предоставляет несколько соседствующих друг с другом установленных версий Python, по одной для каждого проекта. На самом деле он реально не устанавливает различные версии Python, но обеспечивает хитрый способ создать для проектов несколько изолированных друг от друга окружений. Давайте посмотрим, как работает virtualenv.
Если вы работаете с MacOS X или с Linux, есть вероятность, что заработает одна из следующих двух команд:
Возможно, одна из этих команд установит virtualenv на вашей системе. А может быть, это позволит сделать ваш пакетный менеджер. Если вы используете Ubuntu, попробуйте:
Если у вас Windows и команда easy_install не работает, вам необходимо сначала установить её. Чтобы получить дополнительную информацию о том, как это можно сделать, проверьте раздел pip и setuptools в MS Windows . Установив данную команду, запустите её, как указано чуть выше, но без префикса sudo .
После того, как virtualenv была установлена, просто запустите командный интерпретатор и создайте ваше собственное окружение. Обычно в таких случаях я создаю папку проекта, а в ней — папку venv :
Теперь, когда вы захотите работать над проектом, вам необходимо лишь активировать соответствующее окружение. Под MacOS X и Linux, выполните следующее:
Если вы используете Windows, для вас подойдёт следующая команда:
В любом случае, теперь вы должны использовать ваш virtualenv (обратите внимание, как изменилось приглашение вашей командной оболочки — для того, чтобы показать активное окружение).
А если вы захотите вернуться обратно в «реальный мир», используйте команду:
Полсе этого подсказка вашей командной оболочки вернёт свой прежний привычный вид.
Теперь, двинемся дальше. Для того, чтобы Flask появился в вашем виртуальном окружении, введите команду:
Через несколько секунд вы сможете двинуться в дальнейший путь.
Установка непосредственно в систему¶
Возможен и такой вариант установки, но я бы вам его не рекомендовал. Просто запустите pip с привилегиями суперпользователя:
(Под Windows, запустите ту же команду, но только без sudo , внутри окна с командной строкой, запущенного с привилегиями администратора системы)
Жизнь на переднем краю¶
Если вы хотите работать с самой последней версией Flask, существует два пути: можно указать pip , чтобы он загрузил версию для разработки, или можно работать со срезом с текущего состояния репозитория git. В обоих случаях, рекомендуется пользоваться virtualenv.
Получите срез с последнего состояния git в новом окружении virtualenv и запустите в режиме разработки:
Будет скачана и активирована в virtualenv текущая версия, соответствующая последнему (головному) срезу из git. В дальнейшем, чтобы обновиться до последней версии, всё, что вам будет необходимо сделать — это выполнить git pull origin .
pip и setuptools в MS Windows¶
Иногда получение стандартных инструментов по работе с пакетами в Python — таких, как pip, setuptools и virtualenv может быть несколько мудрёным, но на самом деле в этом нет ничего сложного. Вам нужны два ключевых пакета — setuptools и pip — которые позволят вам инсталлировать всё остальное (в том числе virtualenv). К счастью, есть два готовых скрипта, запустив которые вы можете развернуть оба пакета «с нуля».
Если у вас их нет, скрипт get-pip.py осуществит инсталляцию обоих (вам не нужно будет запускать ez_setup.py).
Для инсталляции последней версии setuptools, вы можете использовать следующий скрипт, предназначенный для разворачивания «с нуля»:
Оба этих скрипта необходимо скачать и запустить двойным щелчком мыши. Если у вас уже есть pip, вы можете обновить его, запустив команду:
Чаще всего, получив приглашение командной строки, вы захотите иметь возможность набрать pip и python , что должно привести к запуску этих команд, однако в Windows этого автоматически не происходит, потому что операционная система не знает, где располагаются их исполнимые файлы (вы можете попробовать!).
Чтобы исправить это, вам необходимо перейти в папку, куда вы установили Python (например, C:\Python27 ), а затем в подпапки Tools , Scripts ; затем найти файл win_add2path.py и запустить его. Далее открыть новую Командную строку и проверить, что при вводе python запускается командный интерпретатор.
Наконец, для того, чтобы инсталлировать virtualenv, вы можете просто ввести:
Теперь, когда вы установили всё, что нужно, выполнив вышеизложенные инструкции, можно откинуться на спинку кресла.
Как удалить flask python



Ubuntu — настройка сервера под Flask
Admin
16.09.2020 , обновлено: 04.06.2022
Flask, Ubuntu
1. Установка пакетов для Python
2. Создаем виртуальную среду Python
4. Устанавливаем Flask
5. Настраиваем службу systemd
[ Unit ]
Description =uWSGI instance for ploshadka
After =network.target
[ Service ]
User =ploshadka
Group =www-data
WorkingDirectory = / home / ploshadka / ploshadka.net
Environment = «PATH=/home/ploshadka/ploshadka.net/venv/bin»
ExecStart = / home / ploshadka / ploshadka.net / venv / bin / uwsgi —ini wsgi-config.ini
[ Install ]
WantedBy =multi-user.target
Команды службы uWSGI
6. Настройка Nginx
server <
listen 80 ;
server_name ploshadka.net www.ploshadka.net;
location / <
include uwsgi_params;
uwsgi_pass unix: / home / ploshadka / ploshadka.net / wsgi-socket.sock;
>
>
7. Получаем сертификат Let’s Encrypt для https
Quickstart¶
Eager to get started? This page gives a good introduction to Flask. It assumes you already have Flask installed. If you do not, head over to the Installation section.
A Minimal Application¶
A minimal Flask application looks something like this:
So what did that code do?
First we imported the Flask class. An instance of this class will be our WSGI application.
Next we create an instance of this class. The first argument is the name of the application’s module or package. If you are using a single module (as in this example), you should use __name__ because depending on if it’s started as application or imported as module the name will be different ( ‘__main__’ versus the actual import name). This is needed so that Flask knows where to look for templates, static files, and so on. For more information have a look at the Flask documentation.
We then use the route() decorator to tell Flask what URL should trigger our function.
The function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user’s browser.
Just save it as hello.py or something similar. Make sure to not call your application flask.py because this would conflict with Flask itself.
To run the application you can either use the flask command or python’s -m switch with Flask. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP environment variable:
If you are on Windows, the environment variable syntax depends on command line interpreter. On Command Prompt:
And on PowerShell:
Alternatively you can use python -m flask:
This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see Deployment Options .
Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting.
Externally Visible Server
If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.
If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding —host=0.0.0.0 to the command line:
This tells your operating system to listen on all public IPs.
What to do if the Server does not Start¶
In case the python -m flask fails or flask does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message.
Old Version of Flask¶
Versions of Flask older than 0.11 used to have different ways to start the application. In short, the flask command did not exist, and neither did python -m flask. In that case you have two options: either upgrade to newer Flask versions or have a look at the Development Server docs to see the alternative method for running a server.
Invalid Import Name¶
The FLASK_APP environment variable is the name of the module to import at flask run. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application). It will tell you what it tried to import and why it failed.
The most common reason is a typo or because you did not actually create an app object.
Debug Mode¶
(Want to just log errors and stack traces? See Application Errors )
The flask script is nice to start a local development server, but you would have to restart it manually after each change to your code. That is not very nice and Flask can do better. If you enable debug support the server will reload itself on code changes, and it will also provide you with a helpful debugger if things go wrong.
To enable all development features (including debug mode) you can export the FLASK_ENV environment variable and set it to development before running the server:
(On Windows you need to use set instead of export .)
This does the following things:
it activates the debugger
it activates the automatic reloader
it enables the debug mode on the Flask application.
You can also control debug mode separately from the environment by exporting FLASK_DEBUG=1 .
There are more parameters that are explained in the Development Server docs.
Even though the interactive debugger does not work in forking environments (which makes it nearly impossible to use on production servers), it still allows the execution of arbitrary code. This makes it a major security risk and therefore it must never be used on production machines.
Screenshot of the debugger in action:

More information on using the debugger can be found in the Werkzeug documentation.
Have another debugger in mind? See Working with Debuggers .
Routing¶
Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page.
Use the route() decorator to bind a function to a URL.
You can do more! You can make parts of the URL dynamic and attach multiple rules to a function.
Variable Rules¶
You can add variable sections to a URL by marking sections with <variable_name> . Your function then receives the <variable_name> as a keyword argument. Optionally, you can use a converter to specify the type of the argument like <converter:variable_name> .
(default) accepts any text without a slash
accepts positive integers
accepts positive floating point values
like string but also accepts slashes
accepts UUID strings
Unique URLs / Redirection Behavior¶
The following two rules differ in their use of a trailing slash.
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash, Flask redirects you to the canonical URL with the trailing slash.
The canonical URL for the about endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash produces a 404 “Not Found” error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice.
URL Building¶
To build a URL to a specific function, use the url_for() function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters.
Why would you want to build URLs using the URL reversing function url_for() instead of hard-coding them into your templates?
Reversing is often more descriptive than hard-coding the URLs.
You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs.
URL building handles escaping of special characters and Unicode data transparently.
The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.
If your application is placed outside the URL root, for example, in /myapplication instead of / , url_for() properly handles that for you.
For example, here we use the test_request_context() method to try out url_for() . test_request_context() tells Flask to behave as though it’s handling a request even while we use a Python shell. See Context Locals .
HTTP Methods¶
Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods.
If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC. Likewise, OPTIONS is automatically implemented for you.
Static Files¶
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.
To generate URLs for static files, use the special ‘static’ endpoint name:
The file has to be stored on the filesystem as static/style.css .
Rendering Templates¶
Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the Jinja2 template engine for you automatically.
To render a template you can use the render_template() method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:
Case 1: a module:
Case 2: a package:
For templates you can use the full power of Jinja2 templates. Head over to the official Jinja2 Template Documentation for more information.
Here is an example template:
Inside templates you also have access to the request , session and g 1 objects as well as the get_flashed_messages() function.
Templates are especially useful if inheritance is used. If you want to know how that works, head over to the Template Inheritance pattern documentation. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer).
Automatic escaping is enabled, so if name contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the Markup class or by using the |safe filter in the template. Head over to the Jinja 2 documentation for more examples.
Here is a basic introduction to how the Markup class works:
Changed in version 0.5: Autoescaping is no longer enabled for all templates. The following extensions for templates trigger autoescaping: .html , .htm , .xml , .xhtml . Templates loaded from a string will have autoescaping disabled.
Unsure what that g object is? It’s something in which you can store information for your own needs, check the documentation of that object ( g ) and the Using SQLite 3 with Flask for more information.
Accessing Request Data¶
For web applications it’s crucial to react to the data a client sends to the server. In Flask this information is provided by the global request object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals:
Context Locals¶
If you want to understand how that works and how you can implement tests with context locals, read this section, otherwise just skip it.
Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand.
Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking.
So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use the test_request_context() context manager. In combination with the with statement it will bind a test request so that you can interact with it. Here is an example:
The other possibility is passing a whole WSGI environment to the request_context() method:
The Request Object¶
The request object is documented in the API section and we will not cover it here in detail (see Request ). Here is a broad overview of some of the most common operations. First of all you have to import it from the flask module:
The current request method is available by using the method attribute. To access form data (data transmitted in a POST or PUT request) you can use the form attribute. Here is a full example of the two attributes mentioned above:
What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.
To access parameters submitted in the URL ( ?key=value ) you can use the args attribute:
We recommend accessing URL parameters with get or by catching the KeyError because users might change the URL and presenting them a 400 bad request page in that case is not user friendly.
For a full list of methods and attributes of the request object, head over to the Request documentation.
File Uploads¶
You can handle uploaded files with Flask easily. Just make sure not to forget to set the enctype=»multipart/form-data» attribute on your HTML form, otherwise the browser will not transmit your files at all.
Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the files attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works:
If you want to know how the file was named on the client before it was uploaded to your application, you can access the filename attribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through the secure_filename() function that Werkzeug provides for you:
For some better examples, checkout the Uploading Files pattern.
Cookies¶
To access cookies you can use the cookies attribute. To set cookies you can use the set_cookie method of response objects. The cookies attribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use the Sessions in Flask that add some security on top of cookies for you.
Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the make_response() function and then modify it.
Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the Deferred Request Callbacks pattern.
Redirects and Errors¶
To redirect a user to another endpoint, use the redirect() function; to abort a request early with an error code, use the abort() function:
This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works.
By default a black and white error page is shown for each error code. If you want to customize the error page, you can use the errorhandler() decorator:
Note the 404 after the render_template() call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well.
See Error handlers for more details.
About Responses¶
The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a 200 OK status code and a text/html mimetype. If the return value is a dict, jsonify() is called to produce a response. The logic that Flask applies to converting return values into response objects is as follows:
If a response object of the correct type is returned it’s directly returned from the view.
If it’s a string, a response object is created with that data and the default parameters.
If it’s a dict, a response object is created using jsonify .
If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status) , (response, headers) , or (response, status, headers) . The status value will override the status code and headers can be a list or dictionary of additional header values.
If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object.
If you want to get hold of the resulting response object inside the view you can use the make_response() function.
Imagine you have a view like this:
You just need to wrap the return expression with make_response() and get the response object to modify it, then return it:
APIs with JSON¶
A common response format when writing an API is JSON. It’s easy to get started writing such an API with Flask. If you return a dict from a view, it will be converted to a JSON response.
Depending on your API design, you may want to create JSON responses for types other than dict . In that case, use the jsonify() function, which will serialize any supported JSON data type. Or look into Flask community extensions that support more complex applications.
Sessions¶
In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.
In order to use sessions you have to set a secret key. Here is how sessions work:
The escape() mentioned here does escaping for you if you are not using the template engine (as in this example).
How to generate good secret keys
A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for Flask.secret_key (or SECRET_KEY ):
A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers.
Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this.
Message Flashing¶
Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message.
To flash a message use the flash() method, to get hold of the messages you can use get_flashed_messages() which is also available in the templates. Check out the Message Flashing for a full example.
Logging¶
New in version 0.3.
Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it’s okay to reply with 400 Bad Request in that situation, but sometimes that won’t do and the code has to continue working.
You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use.
Here are some example log calls:
The attached logger is a standard logging Logger , so head over to the official logging docs for more information.
Hooking in WSGI Middleware¶
To add WSGI middleware to your Flask application, wrap the application’s wsgi_app attribute. For example, to apply Werkzeug’s ProxyFix middleware for running behind Nginx:
Wrapping app.wsgi_app instead of app means that app still points at your Flask application, not at the middleware, so you can continue to use and configure app directly.
Using Flask Extensions¶
Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask.
Как удалить flask python
I'm going to give us one more line, and then I'm going to say # Endpoint for deleting a record . Right here, or I should say that just to make sure this is very clear, deleting a record . Just to make it clear you can only delete one at a time. As you may have guessed, we're going to start off with a decorator. So I'm going to say:
The difference is our method is going to be DELETE . With that decorator in place, now we can create a function that is going to take in a specific guide, and then it's going to remove it from the database. So I can say:
Take in an ID as an argument, and then we're going to first perform the query.
From there we're going to start up a session. Make sure you execute it with a parens, and then from there we are simply going to return guide_schema.jsonify(guide) .
Let's save this and let's run it. So python app.py . Run that. Everything looks good so far.

Now, just so you can see right, if we perform our get query on guides and run that, everything here is working. Now what I want to do is I want to remove the second guide here.

The way we would do that is inside of our verb's here, I would come and I would say that I want to delete a record. Then right here with guides, I'm going to say guides/2 because that's the id of the record that we want to remove. Now if I click send, then it says not found which actually makes sense because, right here, we passed this in wrong.

I had another point I was going to make in a second, but let's just fix the endpoint that's supposed to be a single guide/2 . Let's run it one more time, and there we go. This is a little bit interesting, and this is going to be something that is up to you.
In future projects, we're going to talk about it, but whenever you want to remove something, so you want to delete a record, then sometimes you may want to return the entire object like we're doing here.

What I typically do is I will not return the object. I may just return the ID and then a message, such as that guide was successfully deleted . Let's actually do that. I want to, so far I've kind of been following the basic documentation for a lot of this, but let's take a little bit more of a deep dive into this to see what's happening. That may also make a few of the other concepts more clear.
Let's open up this last one. So return , you may think that I have to return this guide_schema , and you can do that, but if you wanted to return something else. Whatever you wanted to say, return and then you just wanted to return some kind of object or anything like that. What if you just want to return a string? So here if you say:
Let's see if this works. Let's say that python app.py . Everything there looks like it's working. Let's add a new guide really quick, so I'm going to go with post and then just post to guide. Go into the body and let's say Another post , this can just have some content , and let's send that. Look like it worked. Let's add one more just so we have a little bit more data to work with. We can say Yet another post .
Now we run a get request for all of the guides. Send. Now you can see we have the three records. We can see that that initial item was deleted, and that did work properly. Usually, you do want to return some type of JSON data for your request, but I didn't want you to think that it was magic behind it.
I'm going to run that delete again. So let's come to delete and let's delete say the guy with the id of 3 . So I'm going to say guide/3 . Let's delete that one. Hit send, and look at that.

We didn't get JSON back, and so we wouldn't really want to do that in real life. What I did want to show you is this isn't magic. All we're doing here is we're working with just regular Python code. When I say return some of that code, like calling the schema and calling JSONIFY in those things, it may seem like you need to memorize every little element that you're going to work on. In reality, this is just python code.
So here when I say return the string, that's what gets returned. I'd definitely recommend for you to play around with quite a bit this code, especially if some of it's confusing to you. Play around with it, see what happens when you change elements.
See what happens if you wanted to say: add conditionals . What if you wanted to make it so a guide would get deleted, but maybe it would archive that and you could go and create some new columns up here. You could create other columns inside of the schema. Create a new schema, add new records, and then go and change the values on a delete. All kinds of things like that.
This is a really good base case for building out an API with Python. It gives you all of the key CRUD functionality that you're going to need. It gives you a database schema. It gives you the ability to create new records, to query all of them, to query a single one, to update, and then to delete.
I don't want you to think that this is just the end-all. This is actually just the beginning, but it's a solid beginning. This is much more than just a hello world , what we did in the first guide, but now you have a fully functional API. You have the ability to call it to work with modern tools such as Postman, and work with JSON data, and all of the various and all the popular HTTP verbs.
This is going to help you as you go through your development career. This is going to be able to give a really firm foundation to you as you build out APIs. Nice work as you went through that, and I look forward to working with you on new projects in the future.