投稿時間:2023-08-08 23:15:18 RSSフィード2023-08-08 23:00 分まとめ(22件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
TECH Techable(テッカブル) 海水浴場の安全監視にドローンを活用!静岡・下田で実証実験、ライフセーバーも参加 https://techable.jp/archives/216460 実証実験 2023-08-08 13:00:29
python Pythonタグが付けられた新着投稿 - Qiita python upgrade package https://qiita.com/aizwellenstan/items/496389606f9a0d0b9157 upgrade 2023-08-08 22:27:18
python Pythonタグが付けられた新着投稿 - Qiita 辞書型の勉強 https://qiita.com/ogigi3/items/0a19956d8a0aaa175f9e cforxinrangedicxxprintdic 2023-08-08 22:00:59
js JavaScriptタグが付けられた新着投稿 - Qiita 見通しを改善!Vue.js でのバリデーション処理のリファクタリング https://qiita.com/sho_fcafe/items/ec6a92cd23d629f8fd12 vuejs 2023-08-08 22:13:22
golang Goタグが付けられた新着投稿 - Qiita Go Interfaceの実装漏れを検知する https://qiita.com/kouji0705/items/2101e07225364d5b3da9 gosrcgosample 2023-08-08 22:46:19
golang Goタグが付けられた新着投稿 - Qiita 【Golang】複数の struct をマージする【小さな構造体をダイナミックに組み合わせたい】 https://qiita.com/KEINOS/items/12896a7803eabe948185 struct 2023-08-08 22:24:57
golang Goタグが付けられた新着投稿 - Qiita GORMでSelect用構造体とPreloadingを併用する https://qiita.com/Cherno/items/d20926227114e5acce86 preloading 2023-08-08 22:24:54
海外TECH MakeUseOf 5 Ways to Play Your Favorite Games on a Mac https://www.makeuseof.com/ways-to-play-games-on-a-mac/ favorite 2023-08-08 13:46:27
海外TECH MakeUseOf The 5 Best AI Extensions for Gmail https://www.makeuseof.com/gmail-ai-extensions/ email 2023-08-08 13:30:32
海外TECH MakeUseOf Threads vs. Mastodon: Which Is Best? https://www.makeuseof.com/threads-versus-mastodon-comparison/ twitter 2023-08-08 13:15:24
海外TECH MakeUseOf Which of Abishkking's Many Home Workout Apps Are Worth Trying? https://www.makeuseof.com/abishkking-many-home-workout-apps-worth-trying/ google 2023-08-08 13:15:24
海外TECH MakeUseOf How to Fix the “Check the PIN” Bluetooth Pairing Error on Windows 11/10 https://www.makeuseof.com/fix-check-the-pin-bluetooth-pairing-error-on-windows/ windows 2023-08-08 13:00:25
海外TECH DEV Community ⚡An Introduction to Using FastAPI https://dev.to/refine/an-introduction-to-using-fastapi-ieh An Introduction to Using FastAPIAuthor Obisike Treause IntroductionSince its introduction to backend development Python has grown in popularity competing with pre existing heavyweights such as PHP and Net It has made the developer experience more efficient and streamlined by introducing simplicity and power Despite being known to be slower than its counterpart Python has thrived greatly in this ecosystem Several frameworks for developing web APIs have been developed such as Django and Flask but the underlying speed problem has always been present As a result another Python framework FastAPI has been developed to combat this issue Steps we ll cover What is FastAPIBenefits of using FastAPIComparing FastAPI with other Python frameworksUnderstanding FastAPI by building a REST API for an inventory applicationAdvanced Concepts in FastAPI What is FastAPIFastAPI is a modern Python microframework that simplifies the creation of web APIs using Python programming It allows developers to swiftly and easily build APIs ensuring optimal performance and easy management without compromising code quality and efficiency It provides numerous advantages including exceptional speed outperforming several other Python backend frameworks and competing with popular frameworks like Express js FastAPI offers the simplicity of Flask as it closely resembles Flask but still packs out of the box configurations such as validation documentation and response encoding Benefits of using FastAPIAs previously emphasized FastAPI stands out due to its exceptional benefits and extensive advantages Let s delve into some of the notable benefits it offers Performance FastAPI maximizes performance by utilizing the full potential of critical libraries and tools such as Pydantic and the ASGI ecosystem Furthermore because of its solid foundation on the Starlette framework it seamlessly integrates the power of async await functionality Scalability The modularity and simplicity of FastAPI allow for seamless integration with load balancers facilitating scalability and ensuring efficient resource utilization Automatic Documentation By requiring the explicit definition of various FastAPI components Pydantic s integration has allowed FastAPI to be able to generate its API documentation automatically FastAPI provides Swagger API documentation Ease of use FastAPI is a Python framework so the benefits of using Python are inherited Not only that FastAPI makes creating your server and building endpoints simple and quick Request Validation FastAPI provides request validation with a much more detailed error message readable by users This is also attributed to its use of Pydantic for request data type specification Comparing FastAPI with other Python frameworksFastAPI a relatively new addition to the backend API ecosystem competes with established Python giants such as Flask and Django While Flask and Django have been recognized as leading frameworks in this space it s important to see how they compare to FastAPI Django Vs FastAPIDjango is a feature rich Python backend framework that includes a variety of built in libraries to meet the needs of various projects It has powerful features like ORM authentication mechanisms and routing capabilities which make it suitable for developing complex web applications FastAPI on the other hand shines as a nimble microframework that was purposefully designed to be lightweight While it lacks a large library ecosystem it compensates by being extremely fast Unlike Django which is limited by its app system FastAPI uses modern Python techniques to unlock its inherent advantages and improve its performance Flask Vs FastAPIFlask is a lightweight framework used by Python developers to quickly build web applications Flask stands out for its design giving developers more control and flexibility when structuring their applications ensuring that the applications are tailored to their specific needs or requirements FastAPI on the other hand focuses on developing highly performant and scalable applications with exceptional speed It has additional benefits discussed in this article and is best suited for complex applications Pyramid Vs FastAPIPyramid is yet another intriguing flavor of one of Python s most popular backend frameworks It adheres to the use only what you need philosophy which means it provides a minimalistic core that can be supplemented with various add ons and libraries This modular approach enables developers to pick and choose which components they need for their specific use cases resulting in a lightweight and highly customizable framework FastAPI on the other hand prioritizes developer productivity and ease of use It has a simple and intuitive API design as well as clear documentation and extensive examples It also comes with some pre built tools such as auto documentation generation Getting StartedWith FastAPI you can easily set up a project in a few steps Firstly like any other Python project you ll need to set up your virtual environment After that you ll need to install the packages FastAPI and Uvicorn To do this run the command python m pip install fastapi uvicorn standard With that you can start creating the endpoints required for your application The packages fastapi and uvicorn are essential for setting up a FastAPI project The package uvicorn creates the server that runs the FastAPI setup while fastapi provides the necessary methods and configurations for creating endpoints Creating your first routeTo create your first route create a file main py which will contain all your code Open the file in your text editor and add the following from fastapi import FastAPIfastapi FastAPI fastapi get async def home return data Hello World In the above snippet you ll notice that you are importing the FastAPI class from the fastapi module and then instantiating the class The instance of the FastAPI class can then be used as a decorator for the handler function to set up the endpoints This instance provides the REST API verbs such as PUT DELETE PATCH GET and POST and a way to set the resource path Once that is done you can run the following command on the terminal to start the server uvicorn main fastapi reloadThe main represents the module import and the fastapi is an instance of the FastAPI The command above starts the server which can then be accessed via the browser at To add another route simply create a handler function e g def handler return data from handler After that using the FastAPI instance you created add the decorator fastapi post home page To the function This converts the function to an API endpoint You can use fastapi post fastapi put or fastapi patch or fastapi delete to create different endpoints Managing request and response bodies using FastAPI modelsSending and receiving data to an endpoint is a fundamental aspect of API development When it comes to the sending aspect there are multiple methods for sending data to an endpoint one of which includes the following Path parameters This method involves attaching short data directly to the URL path To implement this functionality in a FastAPI s endpoint you can refer to the example below other data goes here fastapi get name async def get name name str return name name In the above example the name is a path parameter that is extracted from the URL and passed as a parameter to the get name function This way you can conveniently access the data sent through the URL path Query parameters They are similar to the path parameter but the difference is that the query parameters are appended to the URL after a question mark To implement query parameters in a FastAPI s endpoint you can refer to the example below fastapi get async def get api data data type str skip int limit int return data type data type skip skip limit limit In the above example the skip and limit parameters are query parameters They are provided via the URL after the endpoint using the format key value The skip and limit parameters have default values of and respectively but can be overridden by providing different values in the URL Body parameters This type is different from the previously mentioned It s a method whereby the data is encoded and appended to the request made to the endpoint The body parameter is implemented in the following way from pydantic import BaseModelfrom fastapi import FastAPIfastapi FastAPI class Item BaseModel name str price float fastapi post items async def create item item Item return item item In the above example we define an Item class that inherits from BaseModel provided by Pydantic This system defines the whole request body parameters and provides more context to FastAPI Headers and Cookies One of the major ways of sending extra information for context to the server is through headers and cookies To do this with FastAPI simply follow the example below For Headers from fastapi import FastAPI Headerapp FastAPI app get items async def read items user agent str Header None return User Agent user agent In the above example the user agent parameter is given the default Header None which tells FastAPI to extract the value of the header from the request If the header is present in the request user agent will be set to it otherwise user agent will be set to None For Cookies from fastapi import FastAPI Cookieapp FastAPI app get items async def read items session token str Cookie None return session token session token In this example similarly to headers the session token parameter is given the default value of Cookie None indicating that FastAPI should inject the cookies set on the request into the session token parameter If no cookies are set then the value of the session token will be None Preview the API DocumentationOnce the server is running on the browser visit docs Understanding FastAPI by building a REST API for an inventory applicationTo demonstrate the power of FastAPI you ll be building a REST API for a hypothetical inventory application This API will be connected to a database support image uploads and have protected routes This API will have the following endpoints GET items To fetch all the items stored on the serverGET items item id to get a specific item from the serverPOST items to get add a new item to our serverPATCH items item id to update the item on the serverDELETE items item id to delete an item from the inventoryThen you ll be creating more endpoints to handle the serving of files and you ll also be adding a database and some sort of authentication to some of the endpoints using a middleware PrerequisitesTo follow along you ll need to have the following Knowledge of PythonKnowledge of HTTP JSON REST API and Python s Virtual EnvironmentA terminalPython installed Setting the projectTo do this set up a virtual environment by following the instructions Once done you must create the src directory in the virtual environment folder This is where your code will reside Open the directory using your code editor Open source enterprise application platform for serious web developersrefine new enables you to create React based headless UI enterprise applications within your browser that you can preview tweak and download instantly By visually combining options for your preferred React platform UI framework backend connector and auth provider you can create tailor made architectures for your project in seconds It feels like having access to thousands of project templates at your fingertips allowing you to choose the one that best suits your needs Installing DependenciesYou ll only need essential dependencies such as Uvicorn and FastAPI to accomplish this However since you ll be enhancing the server s capabilities by incorporating a database connection and a file upload system installing additional dependencies like databases and SQLAlchemy is necessary To proceed run the command pip install fastapi all uvicorn standard databases sqlalchemyThis will install all the necessary dependencies for this project Creating Your EndpointsIn your src directory create a new file main py this will be the entry point of your application So on the main py add the following from fastapi import FastAPIfrom fastapi import HTTPExceptionfrom utils import find itemfrom pydantic import BaseModel Fieldfrom typing import Optionalfastapi FastAPI inventory id name Treasure quantity class Item BaseModel name str quantity intclass ItemUpdate BaseModel name Optional str Field None description Optional name of the item quantity Optional int Field None description Optional quantity of the item fastapi get items async def get items return items inventory fastapi get items item id async def get item item id int item idx find item inventory lambda x x id item id return item item fastapi delete items item id async def delete item item id int authenticated bool Depends authenticate item idx find item inventory lambda x x id item id if idx return HTTPException item not found inventory pop idx return item item fastapi post items async def add item data Item item id len inventory name data name quantity data quantity inventory append item return item fastapi patch items item id async def update item item id int item update ItemUpdate item idx find item inventory lambda x x id item id if idx raise HTTPException status code detail Item not found if item update name is not None item name item update name if item update quantity is not None item quantity item update quantity inventory idx item return itemIn the snippet above there are five handlers for the endpoints You have a local inventory data store that saves all the added items The ItemUpdate class specifies the body parameter for the patch endpoint allowing for optional parameters The Optional class from the typing module and the Field class from pydantic are imported for creating these optional fields Add the utility functions to a file utils py in the src directory Following that you can run the server to test the endpoints via the documentation Advanced Concepts in FastAPIAPIs are usually not basic like the inventory API created Sometimes you ll need to persist data or validate credentials before performing requests or handling files For your inventory app you ll be adding the validation middleware the file upload and the database Implementing the Authentication MiddlewareMiddlewares are like the valves of the API world They can be used to do a lot of things like restricting access to certain users adding extra context to the request and many more To demonstrate its capability you are going to create a middleware that allows access to clients that have a certain credential and add it to some of the endpoints of the inventory app Create a new file in the src directory called middleware py and add the following code from fastapi import HTTPException Dependsfrom fastapi security import HTTPBasic HTTPBasicCredentialssecurity HTTPBasic def authenticate credentials HTTPBasicCredentials Depends security correct username admin correct password password if credentials username correct username or credentials password correct password raise HTTPException status code detail Unauthorized return TrueIn the case above the middleware authenticate implements basic authentication To add this to your desired route handler go to the main py file locate the endpoints you want to add authentication and add the parameter authenticated bool Depends authenticate After that the handler will look like this fastapi post items async def add item data Item authenticated bool Depends authenticate item name data name id len inventory quantity data quantity inventory append item return itemEnsure you import the authenticate from the middleware py you created and Depends from fastapi Database IntegrationTo add a database to our existing inventory app we must first ensure that sqlalchemy and databases are installed Then create a file “database py in the src directory Then we need to import the following from sqlalchemy import Column Integer String create enginefrom sqlalchemy ext declarative import declarative basefrom sqlalchemy orm import sessionmakerYou ll be using SQLite due to its simplicity Next you ll need to create the database engine by adding the code to the fileDATABASE URL sqlite database db engine create engine DATABASE URL This is the basic connection configuration for the database After that create the SessionLocal class which creates a database session when called and the Base class which will serve as the BaseModel for all the database models to inherit On the same database py file add the following SessionLocal sessionmaker autocommit False autoflush False bind engine Base declarative base Next create a database model by creating by adding the following class DBItem Base tablename items id Column Integer primary key True index True quantity Column Integer name Column String After that you ll need to import the DBItem and the SessionLocal from the database py file to the main py file Additionally make sure to update the route handlers accordingly fastapi post items def create item item Item authenticated bool Depends authenticate db SessionLocal new item DBItem name item name quantity item quantity db add new item db commit db refresh new item return item new item fastapi get items async def get items db SessionLocal items db query DBItem all return items items fastapi get items item id def get item item id int db SessionLocal item db query DBItem filter DBItem id item id first if not item raise HTTPException status code detail Item not found return item item fastapi patch items item id def update item item id int item ItemUpdate authenticated bool Depends authenticate db SessionLocal db item db query DBItem filter DBItem id item id first if not db item raise HTTPException status code detail Item not found db item name item name db item quantity item quantity db commit db refresh db item return item db item fastapi delete items item id def delete item item id int authenticated bool Depends authenticate db SessionLocal db item db query DBItem filter DBItem id item id first if not db item raise HTTPException status code detail Item not found db delete db item db commit return message Item deleted In the code above you ll notice that you are instantiating the SessionLocal for each endpoint which is then used to perform the database queries After the query is performed you can then commit it to the database for persistence File UploadsWith FastAPI file uploads can be done very easily We ll use our existing API to demonstrate how file uploads and serving can be achieved First you ll have to update the DBItem in your database py file by adding the following class DBItem Base other database fields goes here image src Column String After that on the main py import File and UploadFile from fastapi import os and then import FileResponse from starlette responses After that add the following fastapi patch item image item id async def upload file item id int file UploadFile File db SessionLocal db item db query DBItem filter DBItem id item id first if not db item raise HTTPException status code detail Item not found file path os path join uploads file filename with open file path wb as f f write await file read db item image src file filename db commit db refresh db item return item db item fastapi get static file async def serve file file str return FileResponse os path join uploads file The first route handler in the snippet above updates the image src field of the specified item and uploads the file to the server Then the second serve file handles the file retrieval from the server Starlette offers several other types of responses including the FileResponse which can then be used on the route handler The source code for this inventory API can be found here ConclusionCongratulations on making it this far By now you should have gained valuable insight into using FastAPI to build your backend application FastAPI is an exceptional user friendly and highly effective API development tool It provides the flexibility associated with a microframework and delivers exceptional performance making it an excellent choice for your API development requirements ResourcesFastAPI documentationStarlette documentationPydantic documentation 2023-08-08 13:26:35
海外TECH DEV Community I created my first open source project on github. https://dev.to/redbeardjunior/i-created-my-first-open-source-project-on-github-1fd7 I created my first open source project on github Project DOCKI just uploaded my first opensource project called dock it is still a basic project with a great vision and mission Dock is gonna be a out of the box template roll out to start your new project easy and efficiently as possible My vision and mission for dock is that it will be a handy template to use for different docker project Just enjoy and leave if you like my vision and mission please leave a star Dock repokeep on docking with dock 2023-08-08 13:15:45
Apple AppleInsider - Frontpage News TSMC expected to approve $11 billion Germany chip factory plans https://appleinsider.com/articles/23/08/08/tsmc-expected-to-approve-11-billion-germany-chip-factory-plans?utm_medium=rss TSMC expected to approve billion Germany chip factory plansTSMC is expected to finalize its plan and approve the building of an billion chip plant in Dresden Germany following a Tuesday board meeting Workers outside a TSMC plantApple chip partner TSMC is getting closer to starting work on a new chip production facility in Germany and its board may make a decision soon The TSMC board is expected to meet and make a decision on the plan later on Tuesday Read more 2023-08-08 13:08:14
Apple AppleInsider - Frontpage News Apple buys Foxconn servers for testing its AI services https://appleinsider.com/articles/23/08/08/apple-buys-foxconn-servers-for-testing-its-ai-services?utm_medium=rss Apple buys Foxconn servers for testing its AI servicesApple s artificial intelligence work has now extended to it needing a series of servers for testing and Foxconn is its exclusive supplier Apple is to test AI services which might boost Siri s capabilitiesTim Cook has said that Apple has been working on AI for years and it s Machine Learning tools also pervade everything it does but it hasn t got a ChatGPT like app as rivals have Or at least it doesn t have one outside of internal use Read more 2023-08-08 13:03:04
Apple AppleInsider - Frontpage News iPhone 15 USB-C connectors shown in claimed leak https://appleinsider.com/articles/23/08/08/iphone-15-usb-c-connectors-shown-in-claimed-leak?utm_medium=rss iPhone USB C connectors shown in claimed leakAn image purporting to show USB C connectors for the iPhone range has been leaked further backing up claims that the Lightning port will go It is as close to certain that the iPhone range will replace Lightning with USB C as it can be what with analysts like Ming Chi Kuo insisting it will ーand the EU demanding it happen soon Now a new image from two leakers on X aka Twitter purports to show the USB C charging port components for the iPhone iPhone Plus and iPhone Pro Max Read more 2023-08-08 13:38:53
海外科学 NYT > Science Wegovy Cuts Risk of Heart Problems, Novo Nordisk Trial Says https://www.nytimes.com/2023/08/08/health/wegovy-obesity-drugs-heart-disease.html health 2023-08-08 13:43:22
ニュース BBC News - Home Cyber-attack on UK's electoral registers revealed https://www.bbc.co.uk/news/uk-politics-66441010?at_medium=RSS&at_campaign=KARANGA personal 2023-08-08 13:42:08
ニュース BBC News - Home France 4-0 Morocco: France reach Women's World Cup quarter-finals https://www.bbc.co.uk/sport/football/66425335?at_medium=RSS&at_campaign=KARANGA dream 2023-08-08 13:09:25
ニュース BBC News - Home Women's World Cup 2023: France thrash Morocco to book quarter-final place - highlights https://www.bbc.co.uk/sport/av/football/66395623?at_medium=RSS&at_campaign=KARANGA Women x s World Cup France thrash Morocco to book quarter final place highlightsWatch highlights as France end Morocco s Women s World Cup dream with a win to set up a quarter final clash against co hosts Australia 2023-08-08 13:28:27
ニュース BBC News - Home Gary O'Neil in line for Wolves manager's job as Julen Lopetegui nears exit https://www.bbc.co.uk/sport/football/66437744?at_medium=RSS&at_campaign=KARANGA Gary O x Neil in line for Wolves manager x s job as Julen Lopetegui nears exitWolves boss Julen Lopetegui is poised to leave the club with former Bournemouth manager Gary O Neil set to replace him 2023-08-08 13:46:50

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)