Te tuhi API ki te Python (me te Flask me te RapidAPI)

Te tuhi API ki te Python (me te Flask me te RapidAPI)

Mena kei te panui koe i tenei tuhinga, kua mohio koe ki nga ahuatanga ka puta mai i te whakamahi i te API (Atanga Papatono Tono).

Ma te taapiri i tetahi o te maha o nga API tuwhera ki to tono, ka taea e koe te whakawhānui ake i te mahi o te tono, te whakarangatira ranei ki nga raraunga e tika ana. Engari ka pehea mena ka whakawhanakehia e koe tetahi ahuatanga ahurei e hiahia ana koe ki te tiri ki te hapori?

He ngawari te whakautu: me hiahia koe hanga to ake API.

Ahakoa he ahua uaua tenei i te tuatahi, he tino ngawari. Ka whakaatu matou ki a koe me pehea te mahi ma te whakamahi i te Python.

He aha e hiahia ana koe ki te timata

Hei whakawhanake i tetahi API me:

  • Python3;
  • pounamu — he anga ngawari me te ngawari ki te whakamahi mo te hanga tono paetukutuku;
  • Puka-ONOA he toronga mo te Flask ka taea e koe te whakawhanake tere i te API REST me te iti o te whirihoranga.

Ka mahia te whakaurunga me te whakahau:

pip install flask-restful

Ka tūtohu matou i tetahi akoranga kaupapa whakangungu kore utu mo te hunga timata:
Te whanaketanga bot Telegram i C# — Akuhata 26–28. He akoranga kaha kore utu e taea ai e koe te mohio me pehea te mahi a nga karetao kaiawhina, nga korero mo te mahi me te Telegram API me etahi atu ahuatanga. Ko nga kaiuru pai e toru ka whiwhi 30 rubles mai i Skillbox.

I mua i to tiimata

Ka whakawhanakehia e matou he API RESTful me te taketake Taumahinga CRUID.

Kia tino marama ki te mahi, kia mohio tatou ki nga kupu e rua kua whakahuatia ake nei.

He aha te REST?

REST API (Representational State Transfer) he API e whakamahi ana i nga tono HTTP hei whakawhiti raraunga.

Me tutuki nga API REST ki etahi paearu:

  • Te hoahoanga-kiritaki: Ka mahi tahi te kaihoko me te atanga kaiwhakamahi, ka mahi tahi te tūmau ki te tuara me te rokiroki raraunga. He motuhake te kiritaki me te tūmau, ka taea te whakakapi motuhake mai i tetahi atu.
  • Stateless - karekau he raraunga kiritaki e penapena ki runga i te tūmau. Ko te ahua o te huihuinga kei te taha o te kiritaki.
  • Te Keteroki - Ka taea e nga kaihoko te keteroki i nga whakautu a te tūmau hei whakapai ake i te mahinga katoa.

He aha te CRUD?

nanakia he kaupapa kaupapa e whakaatu ana i nga mahi e wha (te hanga, te panui, te whakahou me te muku).

I roto i te REST API, ko nga momo tono me nga tikanga tono he kawenga mo nga mahi penei i te tuku, te tiki, te tuku, te whakakore.

Inaianei kua mohio tatou ki nga kupu taketake, ka taea e tatou te timata ki te hanga i te API.

Te whanaketanga

Me hanga he putunga korero mo te mohiotanga horihori. Ko AI tetahi o nga hangarau tere tipu i enei ra, a ko Python te taputapu rongonui mo te mahi tahi me AI.

Ma tenei API, ka taea e te kaiwhakawhanake Python te tiki korero mo AI me te whakahihiri i nga mahi hou. Mena he whakaaro nui to te kaiwhakawhanake mo tenei kaupapa, ka taea e ia te taapiri atu ki te putunga.

Me timata ma te kawemai i nga waahanga e tika ana me te whakarite i te Flask:

from flask import Flask
from flask_restful import Api, Resource, reqparse
import random
app = Flask(__name__)
api = Api(app)

I roto i tenei wahanga, Flask, Api me te Rauemi nga karaehe e hiahiatia ana.

Ko te Reqparse he atanga whakamaarama patai a Flask-RESTful... Ka hiahia hoki koe ki tetahi waahanga matapōkere hei whakaatu i te korero matapōkere.

Inaianei ka hangaia e matou he putunga korero mo AI.

Kei ia urunga repo:

  • ID mamati;
  • ingoa o te kaituhi o te whakahua;
  • korero.

I te mea he tauira whakangungu noa tenei, ka penapenahia e matou nga whakaurunga katoa ki te rarangi Python. I roto i te tino tono, ka whakamahia pea e matou he papaunga raraunga.

ai_quotes = [
    {
        "id": 0,
        "author": "Kevin Kelly",
        "quote": "The business plans of the next 10,000 startups are easy to forecast: " +
                 "Take X and add AI."
    },
    {
        "id": 1,
        "author": "Stephen Hawking",
        "quote": "The development of full artificial intelligence could " +
                 "spell the end of the human race… " +
                 "It would take off on its own, and re-design " +
                 "itself at an ever increasing rate. " +
                 "Humans, who are limited by slow biological evolution, " +
                 "couldn't compete, and would be superseded."
    },
    {
        "id": 2,
        "author": "Claude Shannon",
        "quote": "I visualize a time when we will be to robots what " +
                 "dogs are to humans, " +
                 "and I’m rooting for the machines."
    },
    {
        "id": 3,
        "author": "Elon Musk",
        "quote": "The pace of progress in artificial intelligence " +
                 "(I’m not referring to narrow AI) " +
                 "is incredibly fast. Unless you have direct " +
                 "exposure to groups like Deepmind, " +
                 "you have no idea how fast — it is growing " +
                 "at a pace close to exponential. " +
                 "The risk of something seriously dangerous " +
                 "happening is in the five-year timeframe." +
                 "10 years at most."
    },
    {
        "id": 4,
        "author": "Geoffrey Hinton",
        "quote": "I have always been convinced that the only way " +
                 "to get artificial intelligence to work " +
                 "is to do the computation in a way similar to the human brain. " +
                 "That is the goal I have been pursuing. We are making progress, " +
                 "though we still have lots to learn about " +
                 "how the brain actually works."
    },
    {
        "id": 5,
        "author": "Pedro Domingos",
        "quote": "People worry that computers will " +
                 "get too smart and take over the world, " +
                 "but the real problem is that they're too stupid " +
                 "and they've already taken over the world."
    },
    {
        "id": 6,
        "author": "Alan Turing",
        "quote": "It seems probable that once the machine thinking " +
                 "method had started, it would not take long " +
                 "to outstrip our feeble powers… " +
                 "They would be able to converse " +
                 "with each other to sharpen their wits. " +
                 "At some stage therefore, we should " +
                 "have to expect the machines to take control."
    },
    {
        "id": 7,
        "author": "Ray Kurzweil",
        "quote": "Artificial intelligence will reach " +
                 "human levels by around 2029. " +
                 "Follow that out further to, say, 2045, " +
                 "we will have multiplied the intelligence, " +
                 "the human biological machine intelligence " +
                 "of our civilization a billion-fold."
    },
    {
        "id": 8,
        "author": "Sebastian Thrun",
        "quote": "Nobody phrases it this way, but I think " +
                 "that artificial intelligence " +
                 "is almost a humanities discipline. It's really an attempt " +
                 "to understand human intelligence and human cognition."
    },
    {
        "id": 9,
        "author": "Andrew Ng",
        "quote": "We're making this analogy that AI is the new electricity." +
                 "Electricity transformed industries: agriculture, " +
                 "transportation, communication, manufacturing."
    }
]

Inaianei me hanga e matou he karaehe rauemi Tuhituhi hei tautuhi i nga mahi o a maatau tohu mutunga API. I roto i te karaehe me whakaatu e koe nga tikanga e wha: tiki, tuku, tuku, muku.

Me timata ma te tikanga GET

Ka taea e koe te tiki korero motuhake ma te tohu i tana ID, he korero matapōkere ranei ki te kore te ID i tohua.

class Quote(Resource):
    def get(self, id=0):
        if id == 0:
            return random.choice(ai_quotes), 200
        for quote in ai_quotes:
            if(quote["id"] == id):
                return quote, 200
        return "Quote not found", 404

Ko te tikanga GET ka whakahoki i te korero matapōkere mena kei roto i te ID te uara taunoa, i.e. karekau he ID i tohua i te wa e waea ana i te tikanga.

Mena kua tohua, ka rapu te tikanga i waenga i nga tohutoro ka kitea te mea kei roto te ID kua tohua. Mena kaore he mea i kitea, ka whakaatuhia te panui "Kaore i kitea, 404".

Kia mahara: ka whakahokia e te tikanga he mana HTTP o 200 mena i angitu te tono me te 404 mena kaore i kitea te rekoata.

Inaianei me hanga he tikanga POST hei taapiri i tetahi korero hou ki te putunga

Ka whiwhi i te ID o ia korero hou i a koe e pato ana. I tua atu, ka whakamahia e te POST te reqparse ki te tarai i nga tawhā ka uru ki te tinana tono (kaituhi me te tuhi korero).

def post(self, id):
      parser = reqparse.RequestParser()
      parser.add_argument("author")
      parser.add_argument("quote")
      params = parser.parse_args()
      for quote in ai_quotes:
          if(id == quote["id"]):
              return f"Quote with id {id} already exists", 400
      quote = {
          "id": int(id),
          "author": params["author"],
          "quote": params["quote"]
      }
      ai_quotes.append(quote)
      return quote, 201

I roto i te waehere i runga ake nei, i whakaaetia e te tikanga POST te ID korero. Na, ma te whakamahi i te reqparse, ka tikina e ia te kaituhi me te whakahua mai i te patai, ka penapena ki te papakupu params.

Mena kei te noho tonu tetahi korero me te ID kua tohua, ka whakaatu te tikanga i tetahi karere me te waehere 400.

Mena kaore ano kia hangahia he korero me te ID kua tohua, ka hangaia e te tikanga he rekoata hou me te ID me te kaituhi kua tohua, me etahi atu taapiri. Ka taapirihia te urunga ki te rarangi ai_quotes ka whakahoki mai i te urunga me te korero hou me te tohu 201.

Inaianei ka hangaia e matou he tikanga PUT hei whakarereke i tetahi korero i roto i te putunga

def put(self, id):
      parser = reqparse.RequestParser()
      parser.add_argument("author")
      parser.add_argument("quote")
      params = parser.parse_args()
      for quote in ai_quotes:
          if(id == quote["id"]):
              quote["author"] = params["author"]
              quote["quote"] = params["quote"]
              return quote, 200
      
      quote = {
          "id": id,
          "author": params["author"],
          "quote": params["quote"]
      }
      
      ai_quotes.append(quote)
      return quote, 201

Ko te tikanga PUT, he rite ki te tauira o mua, ka tango i te ID me te whakauru me te tarai i nga taapiri korero ma te whakamahi i te reqparse.

Mena kei te noho mai he tohutoro me te ID kua tohua, ka whakahouhia e te tikanga me nga tawhā hou ka whakaputa i te whakahuatanga whakahou me te waehere 200. Mena karekau he whakahuatanga me te ID kua tohua, ka hangaia he rekoata hou me te waehere 201.

Ka mutu, me hanga he tikanga MURU hei tango i tetahi korero kua kore e whakahihiko

def delete(self, id):
      global ai_quotes
      ai_quotes = [qoute for qoute in ai_quotes if qoute["id"] != id]
      return f"Quote with id {id} is deleted.", 200

Ko tenei tikanga ka whiwhi i te ID korero hei whakaurunga me te whakahou i te rarangi ai_quotes ma te whakamahi i te rarangi tiri.

Inaianei kua hangahia e matou nga tikanga katoa, ko nga mea katoa me mahi he taapiri noa he rauemi ki te API, tautuhi i te huarahi, ka whakahaere i te Flask.

api.add_resource(Quote, "/ai-quotes", "/ai-quotes/", "/ai-quotes/<int:id>")
if __name__ == '__main__':
    app.run(debug=True)

Kua rite ta matou Ratonga API REST!

I muri mai, ka taea e tatou te tiaki i te waehere ki te konae app.py ma te whakahaere i roto i te papatohu ma te whakamahi i te whakahau:

python3 app.py

Mena he pai nga mea katoa, ka whiwhi tatou i tetahi mea penei:

* Aratau patuiro: ka
*E rere ana 127.0.0.1:5000/ (Pēhia CTRL+C kia mutu)
* Ka timata ano me te tatauranga
* Kei te kaha te patuiro!
* PIN Debugger: XXXXXXX

Te whakamatautau i te API

Ina hangahia te API, me whakamatauria.

Ka taea tenei ma te whakamahi i te taputapu papatohu curl, te kiritaki Insomnia REST ranei, ma te whakaputa ranei i te API ki runga Rapid API.

Te tuhi API ki te Python (me te Flask me te RapidAPI)

Te whakaputa i to maatau API

Ko RapidAPI te maakete nui rawa atu o te ao neke atu i te 10 API (me te 000 miriona kaiwhakawhanake).

Ko RapidAPI ehara i te mea he atanga kotahi mo te mahi tahi me nga API tuatoru, engari ka taea e koe te whakaputa tere me te ngawari ki a koe ake API.

Ki ki te mahi i tenei, me whakaputa tuatahi koe i runga i etahi tūmau i te whatunga. I roto i to maatau ka whakamahia e matou Heroku. Ko te mahi me te kore e raru, (ka kitea e koe etahi atu korero mo ia i konei).

Me pehea te Whakaputa i to API ki a Heroku

1. Tāuta Heroku.

Ko te mahi tuatahi ko te rehita me te whakauru i te Atanga Raina Whakahau a Heroku (CLI). Ka mahi tenei i runga i te Ubuntu 16+.

sudo snap install heroku —matarohia

Katahi ka takiuru:

takiuru heroku

2. Tāpirihia nga konae e tika ana.

Inaianei me taapiri nga konae hei whakaputa ki tetahi kōpaki i roto i ta maatau tono:

  • requirements.txt me te rarangi o nga waahanga Python e hiahiatia ana;
  • Procfile, e tohu ana he aha nga whakahau me mahia hei whakahaere i te tono;
  • .gitignore - ki te whakakore i nga konae kaore e hiahiatia i runga i te tūmau.

Kei te kōnae requirements.txt nga rarangi e whai ake nei:

  • hapara
  • pounamu-mamae
  • pūpuku

Kia mahara kua taapirihia e matou te gunicorn (Python WSGI HTTP Server) ki te rarangi na te mea me whakahaere ta matou tono ki runga i te tūmau.

Ko te porohita kei roto:

paetukutuku: gunicorn app:app

Nga ihirangi o .giignore:

*.pyc
__pycache__/

Inaianei kua hangaia nga konae, me timata te git repo me te mahi:

git init
git add
git commit -m "First API commit"

3. Waihangatia he tono Heroku hou.

heroku create

Ka pana tatou i te peka matua ki te repo Heroku mamao:

git push heroku master

Ka taea e koe te timata ma te whakatuwhera i te Ratonga API ma te whakamahi i nga whakahau:

heroku ps:scale web=1
heroku open
 

Ka waatea te API ki your-random-heroku-name.herokuapp.com/ai-quotes.

Me pehea te taapiri i to API Python ki te maakete RapidAPI

Ina whakaputaina to ratonga API ki Heroku, ka taea e koe te taapiri atu ki te API tere. I konei tuhinga taipitopito mo tenei kaupapa.

1. Waihangahia he kaute RapidAPI.

Te tuhi API ki te Python (me te Flask me te RapidAPI)

Rēhitahia he kaute kore utu - ka taea tenei ma te whakamahi i Facebook, Google, GitHub.

Te tuhi API ki te Python (me te Flask me te RapidAPI)

2. Tāpirihia te API ki te paewhiri mana.

Te tuhi API ki te Python (me te Flask me te RapidAPI)

3. I muri mai, whakauruhia nga korero whanui mo to API.

Te tuhi API ki te Python (me te Flask me te RapidAPI)

4. I muri i te panui "Apiti API" ka puta he wharangi hou ka taea e koe te whakauru korero mo to maatau API.

Te tuhi API ki te Python (me te Flask me te RapidAPI)

5. Inaianei ka taea e koe te whakauru-a-ringa ki nga tohu mutunga API ka tango ranei kōnae whakakake whakamahi OpenAPI.

Te tuhi API ki te Python (me te Flask me te RapidAPI)

Inaianei me whakarite e tatou nga pito mutunga o to tatou API ki te wharangi Whakamutunga. I a maatau, ko nga tohu mutunga e rite ana ki te kaupapa o CRUD (tiki, whakairi, tuku, muku).

Te tuhi API ki te Python (me te Flask me te RapidAPI)

I muri mai, me hanga e koe he tohu mutunga GET AI Quote e whakaatu ana i te korero matapōkere (mehemea he taunoa te ID), he korero mo te ID kua tohua.

Hei waihanga i tetahi pito, pawhiria te paatene "Waihanga Whakamutunga".

Te tuhi API ki te Python (me te Flask me te RapidAPI)

Ka tukuna ano e matou tenei tukanga mo etahi atu waahanga mutunga API. Heoi ano! Tena koe, kua whakaputaina e koe to API!

Mena kei te pai katoa, ka penei te ahua o te wharangi API:

Te tuhi API ki te Python (me te Flask me te RapidAPI)

mutunga

I roto i tenei tuhinga, i ako matou i te tukanga o te hanga i to ake RESTful API Service in Python, me te tukanga o te whakaputa i te API ki te kapua Heroku me te taapiri atu ki te raarangi RapidAPI.

Engari ko te putanga whakamatautau i whakaatu i nga maataapono taketake o te whakawhanaketanga API - kaore i whakaarohia nga ahuatanga penei i te haumarutanga, te aukati i te he me te tauine.

I te wa e whakawhanake ana i te API tuuturu, me whai whakaaro enei katoa.

Source: will.com

Tāpiri i te kōrero