投稿時間:2023-02-19 23:08:10 RSSフィード2023-02-19 23:00 分まとめ(10件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita Raspberry Pi OS Bullseyeで圧電ブザーでメロディを鳴らす https://qiita.com/pbjpkas/items/438354ae3054466c4df1 passfail 2023-02-19 22:40:26
python Pythonタグが付けられた新着投稿 - Qiita Instagramに投稿した画像のラベル検出 https://qiita.com/charatech_bps/items/97f1962cfd2361a57e95 google 2023-02-19 22:38:19
python Pythonタグが付けられた新着投稿 - Qiita 【GitHub Actions】Job SummaryでGitHub ActionsでのPythonの実行結果を見やすくする https://qiita.com/Geusen/items/dbec1493f690a2290729 githubactions 2023-02-19 22:28:17
python Pythonタグが付けられた新着投稿 - Qiita U.F.O SAをPythonistaで操作する方法(csvファイルとの対応) https://qiita.com/suzu2582/items/09ce4ecda68eb86ee8c7 pythonista 2023-02-19 22:23:08
海外TECH MakeUseOf The 10 Best Harvard Courses You Can Take Online for Free https://www.makeuseof.com/best-free-harvard-courses-online/ courses 2023-02-19 13:30:16
海外TECH DEV Community Build a CRUD Rest API in Python using Flask, SQLAlchemy, Postgres, Docker https://dev.to/francescoxx/build-a-crud-rest-api-in-python-using-flask-sqlalchemy-postgres-docker-28lo Build a CRUD Rest API in Python using Flask SQLAlchemy Postgres DockerLet s create a CRUD Rest API in Python using Flask Python web framework SQLAlchemy ORM Postgres database Docker containerization Docker Compose to run the application and the database in containers If you prefer a video version IntroHere is a schema of the architecture of the application we are going to create We will create endpoints for basic CRUD operations CreateRead allRead oneUpdateDeleteHere are the steps we are going through Create a Flask application using SQLALchemy as an ORM Dockerize the Flask application writing a Dockerfile and a docker compose yml file to run the application and the databaseRun the Postgres database in a container using Docker Compose and test it with TablePlusRun the Flask application in a container using Docker Compose and test it with PostmanWe will go with a step by step guide so you can follow along Create a Flask application using SQLALchemy as an ORMCreate a new folder mkdir flask crud apistep into the folder cd flask crud apiOpen the folder with your favorite IDE I am using VSCode so I will use the command code We need just files for the Flask application including containerization You can create these files in different ways One of them is to create them manually the other one is to create them with the command line touch requirements txt app py Dockerfile docker compose ymlYour folder structure should look like this ️requirements txt fileThe requirements txt file contains all the dependencies of the project In our case we will need just Let s add them to the requirements txt file flaskpsycopg binaryFlask SQLAlchemyShort explanation of the dependencies flask is the Python web framework we are gonna use psycopg binary is the driver to make the connection with the Postgres database Flask SQLAlchemy is the ORM to make the queries to the database app py fileThe app py file is the main file of the application it contains all the endpoints and the logic of the application Populate the app py file as follows from flask import Flask request jsonify make responsefrom flask sqlalchemy import SQLAlchemyfrom os import environapp Flask name app config SQLALCHEMY DATABASE URI environ get DB URL db SQLAlchemy app class User db Model tablename users id db Column db Integer primary key True username db Column db String unique True nullable False email db Column db String unique True nullable False def json self return id self id username self username email self email db create all create a test route app route test methods GET def test return make response jsonify message test route create a user app route users methods POST def create user try data request get json new user User username data username email data email db session add new user db session commit return make response jsonify message user created except e return make response jsonify message error creating user get all users app route users methods GET def get users try users User query all return make response jsonify user json for user in users except e return make response jsonify message error getting users get a user by id app route users lt int id gt methods GET def get user id try user User query filter by id id first if user return make response jsonify user user json return make response jsonify message user not found except e return make response jsonify message error getting user update a user app route users lt int id gt methods PUT def update user id try user User query filter by id id first if user data request get json user username data username user email data email db session commit return make response jsonify message user updated return make response jsonify message user not found except e return make response jsonify message error updating user delete a user app route users lt int id gt methods DELETE def delete user id try user User query filter by id id first if user db session delete user db session commit return make response jsonify message user deleted return make response jsonify message user not found except e return make response jsonify message error deleting user Explanation We are importing Flask as a frameworkrequest to handle the HTTP jsonify to handle the json format not native in Pythonmake response to handle the HTTP responsesflask sqlalchemy to handle the db queriesenviron to handle the environment variablesWe are creating Flask app configuring the database bu setting an environment variable called DB URL We will set it later in the docker compose yml file Then we are creating a User class with an id a username and an email the id will be autoincremented automatically by SQLAlchemy when we will create the users the tablename users line is to define the name of the table in the databaseAn important line is db create all This will synchronize the database with the model defined for example creating an users table Then we have endpointstest just a test routecreate a user create a user with a username and an emailget all users get all the users in the databaseget one user get one user by idupdate one user update one user by iddelete one user delete one user by idAll the routes have error handling for example if the user is not found we will return a HTTP response You can check a video explanation here Dockerize the Flask applicationLet s populate the Dockerfile Dockerfile FROM python slim busterWORKDIR appCOPY requirements txt RUN pip install r requirements txtCOPY EXPOSE CMD flask run host port FROM sets the base image to use In this case we are using the python slim buster imageWORKDIR sets the working directory inside the imageCOPY requirements txt copies the requirements txt file to the working directoryRUN pip install r requirements txt installs the requirementsCOPY copies all the files in the current directory to the working directoryEXPOSE exposes the port CMD flask run host CMD flask run host port sets the command to run when the container starts Docker composeThe term Docker compose might be a bit confusing because it s referred both to a file and to a set of CLI commands Here we will use the term to refer to the file Populate the docker compose yml file yamlversion services flask app container name flask app image dockerhub flask live app build ports environment DB URL postgresql postgres postgres flask db postgres depends on flask db flask db container name flask db image postgres ports environment POSTGRES PASSWORD postgres POSTGRES USER postgres POSTGRES DB postgres volumes pgdata var lib postgresql datavolumes pgdata We just defined services flask appandflask db flask app is the Flask application we just dockerizedflask db is a Postgres container to store the data We will use the official Postgres imageExplanation version is the version of the docker compose file We are using the verwion services is the list of services containers we want to run In this case we have services flask app and flask dbcontainer name is the name of the container It s not mandatory but it s a good practice to have a name for the container Containers find each other by their name so it s important to have a name for the containers we want to communicate with image is the name of the image we want to use I recommend replacing dockerhub with YOUR Dockerhub account it s free build is the path to the Dockerfile In this case it s the current directory so we are using ports is the list of ports we want to expose In this case we are exposing the port of the flask app container and the port of the flask db container The format is host port container portdepends on is the list of services we want to start before this one In this case we want to start the flask db container before the flask app containerenvironment is to define the environment variables for the flask app we will have a database url to configure the configuration For the flask db container we will have the environment variables we have to define when we wan to use the Postgres container we can t change the keys here because we are using the Postgres image defined by the Postgres team volumes in the flask app defines a named volume we will use for persistency Containers are ephimerals by definition so we need this additional feature to make our data persist when the container will be removed a container is just a process volumes at the end of the file is the list of volumes we want to create In this case we are creating a volume called pgdata The format is volume name Run the Postgres container and test it with TablePlusTo run the Postgres container type docker compose up d flask db The d flag is to run the container in detached mode so it will run in the background You should see something like this Docker is pulling downloading the Postgres image on our local machine and it s running a container based on that Postgres image To check if the container is running type bashdocker compose logs If everything is ok you should see something like this If the last line is LOG database system is ready to accept connections it means that the container is running and the Postgres server is ready to accept connections But to be sure let s make another test To show all the containers running and stopped ones type docker ps a The output should be similar to this Now to test the db connection we can use any tool we want Personally I use TablePlus Use the following configuration Host localhostPort User postgresPassword postgresDatabase postgresThen hit Test at the bottom right If you get the message connection is OK you are good to go You can also click Connect and you will see an empty database This is correct Build and run the Flask applicationNow let s build and run the Flask application Let s go back to the folder where the docker compose yml is located and type docker compose build This should BUILD the flask app image with the name defined in the image value In my case it s francescoxx flask live app because that s my Dockerhub username You should replace francescoxx with your Dockerhub username You can also see all the steps docker did to build the image layer by layer You might recognize some of them because we defined them in the Dockerfile Now to check if the image has been built successfully type docker images We should see a similar result with the image we just built ️Run the flask app serviceWe are almost done but one last step is to run a container based on the image we just built To do that we can just type docker compose up flask app In this case we don t use the d flag because we want to see the logs in the terminal We should see something like this Test the applicationLet s test our application First of all let s just go to any browser and visit localhost testYou shoulds see this result note that if you visit localhost you get an error because there is no route associated to this endpoint but by getting an error is a good thing because it means that the server is running Now it s time to test all the endpints using Postman Feel free to use any tool you want If we make a GET request to localhost users we will get an empty array This is correct Create a userNow let s create a user making a POST request to localhost users with the body below as a request body Let s crete another one One more Get all usersNow let s make a GET request to localhost users to get all the users We just created users Get a specific userIf you want to get a specific user you can make a GET request to localhost users lt user id gt For example to get the user with id you can make a GET request to localhost users Update a userIf you want to update a user you can make a PUT request to localhost users lt user id gt For example to update the user with id you can make a PUT request to localhost users with the body below as a request body To check if the user has been updated you can make a GET request to localhost users Delete a userTo delete a user you can make a DELETE request to localhost users lt user id gt For Example to delete the user with id you can make a DELETE request to localhost users To check if the user has been deleted you can make a GET request to localhost usersAs you can see the user with id is not there anymore ConclusionWe made it We have built a CRUD rest API in Python using Flask SQLAlchemy Postgres Docker and Docker compose This is just an example but you can use this as a starting point to build your own application All the code is available in the GitHub repository link in the video description That s all If you have any question drop a comment below Francesco 2023-02-19 13:17:03
海外TECH DEV Community I need your opinion https://dev.to/pulimoodan/i-need-your-opinion-26en I need your opinion Let me introduce myself I am Akbar A self taught programmer from India Who was almost excelled in his studies but always curious about computers and stuffs I decided not to pursue collegeafter high school because most of the under graduation programs in our country is extremely boring Talking about boring we have to study about every freaking subjects in this world even we are doing a specialised program I was doing freelancing in web development since my th grade and a startup recognising my experience contacted me for a Shopify developer role through LinkedIn I am currently working on that firm right now Let s talk about the problemIt s been a year I am working on Shopify for this startup But now I think it s time to move on I need to study something specialised in game or web development and am eagerly looking for the right thing all over the internet Another thing is I am really interested in working with many developers around the world which would be super exciting If anyone of you can suggest me something it would be helpful 2023-02-19 13:15:15
Apple AppleInsider - Frontpage News Daily deals Feb. 19: $200 off 24-inch iMac, $50 off AirPods Pro, $150 off Apple Studio Display, more https://appleinsider.com/articles/23/02/19/daily-deals-feb-19-200-off-24-inch-imac-50-off-airpods-pro-150-off-apple-studio-display-more?utm_medium=rss Daily deals Feb off inch iMac off AirPods Pro off Apple Studio Display moreSome of the hottest deals we found today include off Apple Watch Ultra a SteelSeries Rival and Razer Cynosa bundle off the Roborock Q robot vacuum and more Get money off the Apple Studio Display the inch iMac or the AirPods Pro today The AppleInsider staff searches the internet for can t miss deals at online retailers to create a list of discounts on top tech items including discounts on Apple products TVs accessories and other gadgets We post the most valuable deals in our Daily Deals list to help you save money Read more 2023-02-19 13:08:52
ニュース BBC News - Home Boris Johnson NI intervention not entirely unhelpful, says Mordaunt https://www.bbc.co.uk/news/uk-politics-64695633?at_medium=RSS&at_campaign=KARANGA ireland 2023-02-19 13:12:03
ニュース BBC News - Home Nicola Bulley: Roads closed in search for missing mum https://www.bbc.co.uk/news/uk-england-lancashire-64696365?at_medium=RSS&at_campaign=KARANGA roads 2023-02-19 13:48:28

コメント

このブログの人気の投稿

投稿時間: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件)