使用 Flask 2.0 开发 Web API

2022-01-09 19:23:43   Cyberbolt

文章发布时刻李辉老师的 APIFlask 还在测试阶段,这里记录我使用原生 Flask 开发 Web API 的方案,并记录本项目的目录结构。APIFlask 完成后,我的工作环境将迁移至此。

未来是 微服务 和 云原生 的时代,传统后端渲染正逐渐被 Web API 替代,传统的中心服务器网站也逐步转为以 Go / Python 为主的云原生应用,容器技术发展势不可挡。本文主要研究使用 Flask 来开发 JSON API,如需了解 Docker 部署 Flask 程序的方案,请点击此处

运行环境:Python 3.8.6, Flask 2.0.2

 

下面简要记录 Flask 2.0 配置静态页面 和 JSON API 的方法

示例项目的目录结构

app.py 该项目的入口模块(使用 python app.py 即可运行程序)

route.py 保存该项目所有页面 (HTML) 的映射路径

static 静态文件的起始目录

static/index.html 测试页面

blueprints 蓝图模块

blueprints/__init__.py 蓝图模块的构造文件

blueprints/front.py 保存网站前台的所有 API

 

源码展示

app.py

from route import app


if __name__ == '__main__':
    app.run(host='127.0.0.1', port='5000', debug=True)

 

route.py

'''
    该模块存放本站所有页面路径
'''
from flask import Flask

from blueprints import front


def creat_app():
    app = Flask(
        __name__,
        static_folder='static',  # 静态文件的目录
        static_url_path='',  # 静态文件目录在链接的起始位置 
    )
    app.register_blueprint(front) #导入home蓝本
    return app


app = creat_app()


@app.route('/')
def home():
    return app.send_static_file('index.html')

static_folder 和 static_url_path 参数将静态文件根目录 /static 替换为 / 。如,默认设置中 index.html 的地址为 127.0.0.1:5000/static/index.html ,此设置地址改为了 127.0.0.1:5000/index.html 或 127.0.0.1:5000 (访问其一均可到达该页面)

 

static/index.html

<!doctype html>
<html lang="zh-CN">
  <head>
    <!-- 必须的 meta 标签 -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap 的 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- JavaScript 文件是可选的。从以下两种建议中选择一个即可! -->

    <!-- 选项 1:jQuery 和 Bootstrap 集成包(集成了 Popper) -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>

    <!-- 选项 2:Popper 和 Bootstrap 的 JS 插件各自独立 -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous"></script>
    -->
  </body>
</html>

访问效果

 

blueprints/__init__.py

from blueprints.front import front

 

blueprints/front.py

'''
    保存网站前台 API
'''
from flask import Flask, Blueprint, jsonify

#蓝图配置
front = Blueprint(
    'front', 
    __name__
)


@front.get('/api/test')
def test():
    return jsonify({
        'code': 1,
        'content': 'api test'
    })

Flask 蓝图配置,该模块存放 front 前台的所有 API,此处加入 Flask 2.0 语法,GET 方法 和 POST 方法配置更为便捷。/api/test 的数据交互格式为 JSON,这里用到 jsonify 将字典转为 JSON。

访问效果

 

配置完成!感谢您的阅读

Milton
2022-03-23 02:54:06

It is with sad regret to inform you DataList.biz is shutting down on 25 March 2022. We have made available databases per country for all companies available.. You can view our samples and download databases instantly on our website DataList.biz


Marian
2022-03-31 15:24:27

回复 Milton: It is with sad regret to inform you that BusinessLeads101.com is shutting down. We have over 300 million records available for a one time fee of $149. Please visit our website BusinessLeads101.com Regards, Marian

Wilson
2022-04-13 00:55:03

回复 Marian: Hello. We are offering Bullet Proof SMTP servers that never get suspended. Email as much as you want. DMCA ignored, bulletproof locations, 100% uptime guaranteed, unlimited data transfer, and 24/7/365 support. 100 Spots available. BulletProofSMTP.org

Leland
2022-04-20 01:45:51

回复 Wilson: Hello. It is with sad regret to inform you TopDataList.com is shutting down. We have made all our databases available for you for a once off fee. Visit us on TopDataList.com

Rick
2022-05-06 19:19:03

回复 Leland: Hello, from CustomData.click we are a provider of unique databases that could help your business. Please visit us at CustomData.click to see if we can help you. Regards, Rick

Jim
2022-05-18 00:07:19

回复 Rick: Hi, my name is Jim from TopDataList.com We are ceasing operations on TopDataList.com and have made our leads available at a discounted price. Visit us on TopDataList.com Regards, Jim

Zita
2022-06-23 02:10:16

回复 Jim: Hello, did you know that there are 241,120 internet directories in the world. These websites are what drive traffic to YOUR business. Want more traffic? Want more Sales? We can help - today. Your website cyberlight.xyz is listed in only 96 of these directories. Get more traffic for your Global audience. Our automated system adds your website to all of the directories. You can find it here: getlisted.directory/cyberlight.xyz Act today, and we will expedite your listings and waive the processing charge!

Kristina
2022-07-06 09:22:55

回复 Zita: Convert cyberlight.xyz to an app with one click! 80% of users browse websites from their phones. Have the App send out push notifications without any extra marketing costs! MakeMySiteMobile.com

Lacey
2022-07-12 19:55:54

回复 Kristina: Hello, did you know that there are 241,120 internet directories in the world. These websites are what drive traffic to YOUR business. Want more traffic? Want more Sales? We can help - today. Your website cyberlight.xyz is listed in only 96 of these directories. Get more traffic for your Global audience. Our automated system adds your website to all of the directories. You can find it here: getlisted.directory/cyberlight.xyz Act today, and we will expedite your listings and waive the processing charge! We have a special going on. Use "FRIENDS" on checkout for a 50% discount valid today.

Meredith
2022-11-12 03:20:33

回复 Lacey: Hi, We can skyrocket your Google rankings in a short time with completely whitehat links and technical seo service. Please check our profile on fiverr: https://go.fiverr.com/visit/?bta=570412&brand=fiverrhybrid&landingPage=https2F%2Fwww.fiverr.com2Fmanually-build-150-high-pr-backlinks Please check tons of 5 star reviews on our Fiverr gig

Jacki
2022-11-22 05:03:10

回复 Meredith: Hi, This AI content writer is less than $90 one time payment for lifetime usage. You can write engaging articles, product descriptions, social media posts, emails, company bio, stories, ads, and 57 other content categories in minutes. It is trained by Jasper AI data and 100M articles and scientific journals and uses the same tech (GPT3): https://appsumo.8odi.net/GjLE5m

Beatriz
2022-11-23 14:52:37

回复 Jacki: Hi cyberlight.xyz team, I can rank your webpages on the first page (the top 3 rankings) of Google with on page and off page SEO service that follows Google guidelines. Never lose your rankings. https://go.fiverr.com/visit/?bta=570412&brand=fiverrhybrid&landingPage=https2F%2Fwww.fiverr.com%2Fjeremymass_seo%2Fdo-seo-for-any-website-ranking-in-just-10-days-or-money-back Monthly packages include: On Page : - Content Optimization - Images optimization - Meta Tags and H1,H2 Optimization - Permalink Set Up - Fix Broken Links or 404 Errors - Create XML Sitemap - Fix Canonical Issue - Speed Optimization Off Page: - Omnichannel Marketing - High quality backlinks from domains with real visitors 5 keywords ranked on top 3 on Google: $120 10 keywords ranked on top 3 on Google: $230 20 keywords ranked on top 3 on Google: $320 Let me know if you have any questions. Rank your webpages now.

Rubye
2022-11-26 03:09:07

回复 Beatriz: We created the most advanced AI content creation and optimization tool following SEO practices. It is better than Jasper and SurferSEO. Your content will rank on Google first page. It will plan your content strategy, and create your content. https://appsumo.8odi.net/QOo623 NLP content optimization: You can edit your old or new content and get them rank with this tool. It has a plagiarism checker as good as copyscape. Lifetime licence. 60 days money back guarantee.

Horacio
2022-11-27 11:56:03

回复 Rubye: Hi there, I will develop a unique and bug-free top-level NFT website for you: NFT minting website, smart contract and web 3 integration https://go.fiverr.com/visit/?bta=570412&brand=fiverrhybrid&landingPage=https2F%2Fwww.fiverr.com2Fcreate-a-responsive-website-with-react-js Service Includes: NFT minting functionality Smart contract development (erc721, erc721a, erc1155) Listing on Opensea and Rarible Connect wallet functionality NFT metadata generation ( art is provided by you ) NFT metadata upload to IPFS Whitelist/Presale using merkle tree technology Ability to mint directly with credit card Blockchains: Solana Ethereum Polygon Binance Smart Chain Avalanche Website Frontend: React JS / Next JS Some reviews: "By far one of the best developers, I have come across and went above and beyond to make sure that everything was perfect for our launch. Great communication and a will to do things the right way. Will definitely be using again and HIGHY RECCOMEND!" "It's my second time ordering from him I needed a front page for my website this time and Josiah did a stellar job with the UI and coding. If you're looking for a detail-oriented dev who knows what he's doing, this is definitely the place to go." "He did an amazing job for us, I can highly recommend him! He explained us everything and everything worked as described! If you search someone for your NFT project, do it with him!"

Norberto
2022-12-09 12:24:19

回复 Horacio: This message below is written by our AI without manual editing: Are you looking for a way to make your content stand out from the crowd and help your website rank higher on Google? Look no further - we have the perfect solution for you. Introducing our AI content writing tool that has over 60 AI content tools, including long form posts, ads, products, poem, descriptions, blog titles, outlines, intros, body, conclusions, ad copy writer, social media content creator, SEO improver, and unique related image generator. This AI content writing tool is the perfect way to create content that will stand out and help your website rank higher on Google. It will also generate unique images related to the keywords and descriptions you provide. You can create unlimited content as there is no word limit. Take your website to the next level and start creating content that will help it rank higher on Google. Get with the times and start using AI content writing with SEO capabilities today. If you would like to find out more about our AI content writing tool and its capabilities: https://appsumo.8odi.net/x94kQA Features in short: - Lifetime, unlimited words - 60+ AI content cretion tools - SEO powered writer, improver and editor - Ultimate SERP tool: Competitor analysis with top 10 of SERP, analyzes with NLP, and helps create content on them - Unique image generator - 60 days money back guarantee

Earle
2022-12-16 19:39:06

回复 Norberto: Hello cyberlight.xyz, We noticed you are only listed in 18 out of a possible 10k+ directories. You can view your ranking here: https://getlisted.directory/cyberlight.xyz?id=MTg= Gift your business this Christmas by submitting your website to 10K+ directories on getlisted.directory. Get more traffic, leads and sales by having your business rank high on search engines. Never has it been easier to promote your website. We've automated everything that we possibly could to make submitting your website a breeze. Visit us on https://getlisted.directory and get submitted 10k+ directories. We have a festive promotional offer for an All Inclusive, One-Time Fee Of $49!

Ethan
2022-12-21 22:39:51

回复 Earle: Last 2 days to grab the best ai writer with GPT-3. Jasper and Surfer SEO alternative. This message below is written by our AI without manual editing: Are you looking for a way to make your content stand out from the crowd and help your website rank higher on Google? Look no further - we have the perfect solution for you. Introducing our AI content writing tool that has over 70 AI content tools, including long form posts, ads, products, poem, descriptions, blog titles, outlines, intros, body, conclusions, ad copy writer, social media content creator, SEO improver, and unique related image generator. This AI content writing tool is the perfect way to create content that will stand out and help your website rank higher on Google. It will also generate unique images related to the keywords and descriptions you provide. You can create unlimited content as there is no word limit. Take your website to the next level and start creating content that will help it rank higher on Google. Get with the times and start using AI content writing with SEO capabilities today. If you would like to find out more about our AI content writing tool and its capabilities: https://appsumo.8odi.net/x94kQA Human summary: Features in short: - Lifetime, unlimited words - 70+ AI content cretion tools - SEO powered writer, improver and editor - Ultimate SERP tool: Competitor analysis with top 10 of SERP, analyzes with NLP, and helps create content on them - Unique image generator - 60 days money back guarantee

Gilbert
2022-12-22 21:37:57

回复 Ethan: Hi, Monitor traffic forecasts, keywords and URLs, growth trends, and heat maps in 10 LANGUAGES with detailed SEO reports sent to your email for only USD19 lifetime licence. https://appsumo.8odi.net/AozjvJ Alternative to - Ahrefs - SEMrush - SurferSEO It gives you everything you need to monitor UNLIMITED KEYWORDS, core keywords, and brand-related keywords. Keep tabs on growth trends for top URLs and keywords, as well as keyword evolution maps, so your content strategy is always on point. You can even calculate the performance of URLs, folders, and subdomains to tackle any immediate issues head on! ** Instead of spending hours identifying priorities and opportunities, let SEOcrawl generate actionable SEO reports on the spot. Features included in all plans - Actionable SEO reports - Download data (CSV, Excel, Google Sheets) - Task management for users - Keyword, URL, and folder rank tracker - Automatic weekly and monthly SEO report - 10 languages and all future languages supported (English, French, German, Italian, Spanish, Romanian, Turkish, Polish, Russian) - SEO extension for Google Chrome - SEO insights with AI and automated analysis

Linette
2022-12-26 06:25:56

回复 Gilbert: Youtube你一定喜歡的主播頻道: https://www.youtube.com/@enjoylifehk 【Minana呀】※推薦※ 皮衣兔女郎,等不及的直接看高潮_ 斗魚直播熱舞: https://www.youtube.com/watch?v=ell2orapuBw 【Minana呀】0_15抖胸配樂完美契合 身材像個大漏斗������ 一次性看過癮! _ 斗魚直播熱舞大擺錘: https://www.youtube.com/watch?v=yHcfmQsxebg

Milagro
2022-12-29 06:37:19

回复 Linette: Hey, AI Creates An Online ‘Ready-To-Profit’ Business Using Just A Keyword & much More. Use In Your Business or Sell To Clients For Big Bucks! Watch AI Takes Over Your Marketing >>> https://bit.ly/millionaire2023weapon Only Check it out if you want to Upgrade your Income to Next Level in 2023. Cheers

Jed
2022-12-29 14:13:34

回复 Milagro: Hey, AI Creates An Online ‘Ready-To-Profit’ Business Using Just A Keyword & much More. Use In Your Business or Sell To Clients For Big Bucks! Watch AI Takes Over Your Marketing >>> https://bit.ly/millionaire2023weapon Only Check it out if you want to Upgrade your Income to Next Level in 2023. Cheers

Klara
2022-12-30 20:51:49

回复 Jed: Hey, Why not gift yourself something that is WORTH more than a Dozen Team Members? Yes, i mean, if 1 AI can do multi tasks which require over a dozen human hands. Wouldn't it be a Big Cash Saver and Time Saver ? I bet this would be a Biggest Gift you can gift yourself. Don't let this Offer Go away : https://bit.ly/rockstarai Happy New Year 2023

Marylyn
2023-01-02 00:30:55

回复 Klara: Hi, Automatically create short, highly-sharable branded videos from your long form content. Quick, easy & cost-effective. No technical skills or software download required. Get Started here >>> https://bit.ly/airevolution2023 Happy New Year 2023 !!!

Adrienne
2023-01-03 00:59:28

回复 Marylyn: Hey How are you doing ? I know you are waiting for this ? Check it out >>> https://bit.ly/newyear2023deals Happy New Year !!!

Ofelia
2023-01-10 14:37:39

回复 Adrienne: Hello cyberlight.xyz, We noticed you are only listed in 18 out of a possible 10k+ directories. You can view your ranking here: https://directoryregistar.info/cyberlight.xyz?id=MTg= Get more traffic, leads and sales by having your business rank high on search engines. We've automated everything that we possibly could to make submitting your website a breeze. Visit us on https://directoryregistar.info and get submitted 10k+ directories. We have a promotional offer running an All Inclusive, One-Time Fee Of $79!

Lasonya
2023-01-13 01:45:41

回复 Ofelia: Hello, I would like to Inquire about the following service: This service: https://www.google.com.hk/search?q=債務重組+李建民事務所幫到你&source=hp&ei=&oq=債務重組+李建民事務所幫到你&gs_lcp=&sclient=mobile-gws-wiz-hp&hl=zh-TW Best, Lasonya

Emelia
2023-01-22 09:06:25

回复 Lasonya: Hey How are you doing ? Do you shop with Amazon ? If No, plz ignore this message. If Yes, You would definately love these Limited Time Exclusive Discounts: https://bit.ly/2023bestdeals Cheers!!

Xiomara
2023-02-01 01:16:52

回复 Emelia: Hey! And it’s LIVE! Recurring Commission System has officially opened to the public! >>> https://www.xoxourl.com/reccomm Recurring Commission System is the 1st and ONLY software solution that makes it easy for ANYONE to bank multiple income streams and build their list at the same time! This cloud based app provides you with your very own stunning site that includes a professional video & details showing visitors what they need to know about essential web tools ... With links that get you paid recurring commissions from up to 18 different services. It also directs visitors to optin for a free training webinar … where you make $1000 from EVERY purchase. Just grab THIS to take home the BIG paydays! >>> https://www.xoxourl.com/reccomm Here’s what you get: DFY, PROFESSIONAL website optimized for recurring, passive AND high ticket commissions MULTIPLE income streams: you’re pre-approved to profit from the 18 recurring services AND high-ticket offer built into your site Free viral traffic & hosting included = ZERO overhead costs Set & forget method: customize your site ONCE, then it runs on 100% autopilot Completely beginner friendly: no tech skills needed, nothing to install, step-by-step instructions included Easy to scale: Recurring Commission System INCLUDES the core software so you can customize this system to fit ANY offer Enjoy!

Bruce
2023-02-04 02:10:17

回复 Xiomara: Claim your $500 Google Ad Credit + FREE 7 Day Trial https://www.xoxourl.com/adcreativeAI Unlock the true potential of your Marketing Agency. Marketing agencies: Wouldn’t it be nice if those Ad Creatives just…created themselves? ... WITHOUT outsourcing to an EXPENSIVE graphic designer? Brand NEW AI generates winning creatives in no time flat at an unbeatable price. Use the power of AI to win the hearts and wallets of your client’s audiences. Claim a $500 Google Ad Credit + FREE 7-day trial now -> https://www.xoxourl.com/adcreativeAI Cheers!!!

Christen
2023-02-05 11:30:37

回复 Bruce: Hey! Are You Ready To Use Instagram ‘Stories’ Get Huge Followers, Traffic, And Make Unlimited Sales On Autopilot? If Your Answer Is "YES" Please Click here: https://bit.ly/instagramstries Cheers

Elke
2023-02-06 11:13:22

回复 Christen: Hey, I hope you're doing well. I'm a representative from Copy.AI and I'm contacting businesses, creators, and teams to introduce them to the most powerful AI-driven content platforms out there. This AI-driven tool will greatly reduce the amount of time you spend and effort writing your content in a matter of seconds, that's right, SECONDS! Think of the time you'd have to focus on other vital tasks like networking, expanding your business, and enhancing growth. Copy.AI is an easy-to-use and intuitive tool that helps you generate content quickly and accurately. Think of a topic and the AI will generate content with just a press of a button. It can also be used to write many different types of copy, such as emails, blog articles, video scripts, social media ads, product descriptions, website content, captions and so much more. Even write in over 25+ different languages. It's designed with content writers in mind, so you can trust that it will provide you with top-notch content every time. Plus, the AI takes into account your target audience so that the content will be tailored to their needs. And guess what - The generated content is devoid of any plagiarism! How about that? These features and benefits are just the tip of the iceberg; there are so many more things you can do with it that it will simply blow you away. So if you're seeking a way to simplify and reduce the amount of time and energy invested without compromising on the quality of your content, give Copy.AI a spin. Thanks for your time and I hope you find Copy.AI a useful companion for your content-writing needs. Cheers, Elke P.S. This was created using Copy.AI. Find out for yourself, I'm confident you'll love it: https://bit.ly/copyaigiveitago