Skip to content

Commit f0429b5

Browse files
Secound Commit
1 parent 6d19ed8 commit f0429b5

29 files changed

+40103
-0
lines changed

.gitignore

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
3+
4+
# dependencies
5+
frontend/node_modules
6+
frontend/.pnp
7+
frontend/.pnp.js
8+
9+
# testing
10+
frontend/coverage
11+
12+
# production
13+
frontend/build
14+
15+
# misc
16+
frontend/.DS_Store
17+
frontend/.env.local
18+
frontend/.env.development.local
19+
frontend/.env.test.local
20+
frontend/.env.production.local
21+
22+
frontend/npm-debug.log*
23+
frontend/yarn-debug.log*
24+
frontend/yarn-error.log*
25+
26+
27+
fastapi-pro/fastapi-venv/
28+
fastapi-pro/.vscode/
29+
fastapi-pro/__pycache__/

fastapi-pro/main.py

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
from fastapi import FastAPI, HTTPException, status
2+
from objects import *
3+
from schemas import Post, UpdatePost
4+
from fastapi.middleware.cors import CORSMiddleware
5+
6+
app = FastAPI()
7+
8+
9+
origins = [
10+
"*",
11+
]
12+
13+
app.add_middleware(
14+
CORSMiddleware,
15+
allow_origins=origins,
16+
allow_credentials=True,
17+
allow_methods=["*"],
18+
allow_headers=["*"],
19+
)
20+
21+
22+
# 127.0.0.1:8000/posts
23+
# 127.0.0.1:8000/posts/{ID}
24+
# 127.0.0.1:8000/get-posts-by-category/network
25+
# 127.0.0.1:8000/search
26+
27+
28+
@app.get("/")
29+
def home():
30+
return {"Data": "Hello World!"}
31+
32+
33+
@app.get("/posts")
34+
def get_posts():
35+
post_list = []
36+
for post_id in post_objects:
37+
post_list.append(post_objects[post_id])
38+
if post_list:
39+
return post_list
40+
else:
41+
raise HTTPException(status_code=404, detail="There are not any posts.")
42+
43+
44+
@app.get("/posts/{ID}")
45+
def get_post(ID: int):
46+
for post_id in post_objects:
47+
if post_id == ID:
48+
return post_objects[post_id]
49+
50+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
51+
52+
53+
@app.get("/get-posts-by-category/{category}")
54+
def get_posts_by_category(category: str):
55+
post_list = []
56+
for post_id in post_objects:
57+
if post_objects[post_id]["category"] == category:
58+
post_list.append(post_objects[post_id])
59+
60+
if post_list:
61+
return post_list
62+
else:
63+
return {"Data": "Not found any post by this category"}
64+
65+
66+
@app.get("/search")
67+
def get_posts_by_search(keyword: str):
68+
post_list = []
69+
for post_id in post_objects:
70+
if (
71+
keyword in post_objects[post_id]["title"]
72+
or keyword in post_objects[post_id]["body"]
73+
):
74+
post_list.append(post_objects[post_id])
75+
if post_list:
76+
return post_list
77+
else:
78+
return {"Data": "there is not any post."}
79+
80+
81+
@app.post("/new-post/{ID}")
82+
def create_post(ID: int, post: Post):
83+
if ID in post_objects:
84+
raise HTTPException(status_code=400, detail="Post ID is already exists")
85+
86+
post_objects[ID] = {
87+
"title": post.title,
88+
"body": post.body,
89+
"category": post.category,
90+
}
91+
return post_objects[ID]
92+
93+
94+
@app.put("/update-post/{ID}")
95+
def update_post(ID: int, post: UpdatePost):
96+
if ID not in post_objects:
97+
raise HTTPException(status_code=404, detail="There is no any post by this ID")
98+
99+
if post.title != None:
100+
post_objects[ID]["title"] = post.title
101+
102+
if post.body != None:
103+
post_objects[ID]["body"] = post.body
104+
105+
if post.category != None:
106+
post_objects[ID]["category"] = post.category
107+
108+
return post_objects[ID]
109+
110+
111+
@app.delete("/delete-post/{ID}")
112+
def delete_post(ID: int):
113+
if ID not in post_objects:
114+
raise HTTPException(status_code=404, detail="There is no any post by this ID")
115+
116+
del post_objects[ID]
117+
return {"Data": "Post successfully deleted"}

fastapi-pro/objects.py

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
post_objects = {
2+
1: {
3+
'id': 1,
4+
"title": "What is django",
5+
"body": """Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. Built by experienced developers, Django takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It is free and open source, has a thriving and active community, great documentation, and many options for free and paid-for support.
6+
7+
Django helps you write software that is:
8+
9+
Complete
10+
Django follows the "Batteries included" philosophy and provides almost everything developers might want to do "out of the box". Because everything you need is part of the one "product", it all works seamlessly together, follows consistent design principles, and has extensive and up-to-date documentation.
11+
12+
Versatile
13+
Django can be (and has been) used to build almost any type of website — from content management systems and wikis, through to social networks and news sites. It can work with any client-side framework, and can deliver content in almost any format (including HTML, RSS feeds, JSON, XML, etc). The site you are currently reading is built with Django!
14+
15+
Internally, while it provides choices for almost any functionality you might want (e.g. several popular databases, templating engines, etc.), it can also be extended to use other components if needed.
16+
17+
Secure
18+
Django helps developers avoid many common security mistakes by providing a framework that has been engineered to "do the right things" to protect the website automatically. For example, Django provides a secure way to manage user accounts and passwords, avoiding common mistakes like putting session information in cookies where it is vulnerable (instead cookies just contain a key, and the actual data is stored in the database) or directly storing passwords rather than a password hash.
19+
20+
A password hash is a fixed-length value created by sending the password through a cryptographic hash function. Django can check if an entered password is correct by running it through the hash function and comparing the output to the stored hash value. However due to the "one-way" nature of the function, even if a stored hash value is compromised it is hard for an attacker to work out the original password.
21+
22+
Django enables protection against many vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request forgery and clickjacking (see Website security for more details of such attacks).
23+
24+
Scalable
25+
Django uses a component-based “shared-nothing” architecture (each part of the architecture is independent of the others, and can hence be replaced or changed if needed). Having a clear separation between the different parts means that it can scale for increased traffic by adding hardware at any level: caching servers, database servers, or application servers. Some of the busiest sites have successfully scaled Django to meet their demands (e.g. Instagram and Disqus, to name just two).
26+
27+
Maintainable
28+
Django code is written using design principles and patterns that encourage the creation of maintainable and reusable code. In particular, it makes use of the Don't Repeat Yourself (DRY) principle so there is no unnecessary duplication, reducing the amount of code. Django also promotes the grouping of related functionality into reusable "applications" and, at a lower level, groups related code into modules (along the lines of the Model View Controller (MVC) pattern).
29+
30+
Portable
31+
Django is written in Python, which runs on many platforms. That means that you are not tied to any particular server platform, and can run your applications on many flavours of Linux, Windows, and Mac OS X. Furthermore, Django is well-supported by many web hosting providers, who often provide specific infrastructure and documentation for hosting Django sites.""",
32+
"category": "webdesign",
33+
},
34+
2: {
35+
'id': 2,
36+
"title": "What is OSPF",
37+
"body": """The OSPF (Open Shortest Path First) protocol is one of a family of IP Routing protocols, and is an Interior Gateway Protocol (IGP) for the Internet, used to distribute IP routing information throughout a single Autonomous System (AS) in an IP network.
38+
The OSPF protocol is a link-state routing protocol, which means that the routers exchange topology information with their nearest neighbors. The topology information is flooded throughout the AS, so that every router within the AS has a complete picture of the topology of the AS. This picture is then used to calculate end-to-end paths through the AS, normally using a variant of the Dijkstra algorithm. Therefore, in a link-state routing protocol, the next hop address to which data is forwarded is determined by choosing the best end-to-end path to the eventual destination.
39+
The main advantage of a link state routing protocol like OSPF is that the complete knowledge of topology allows routers to calculate routes that satisfy particular criteria. This can be useful for traffic engineering purposes, where routes can be constrained to meet particular quality of service requirements. The main disadvantage of a link state routing protocol is that it does not scale well as more routers are added to the routing domain. Increasing the number of routers increases the size and frequency of the topology updates, and also the length of time it takes to calculate end-to-end routes. This lack of scalability means that a link state routing protocol is unsuitable for routing across the Internet at large, which is the reason why IGPs only route traffic within a single AS.
40+
Each OSPF router distributes information about its local state (usable interfaces and reachable neighbors, and the cost of using each interface) to other routers using a Link State Advertisement (LSA) message. Each router uses the received messages to build up an identical database that describes the topology of the AS.
41+
From this database, each router calculates its own routing table using a Shortest Path First (SPF) or Dijkstra algorithm. This routing table contains all the destinations the routing protocol knows about, associated with a next hop IP address and outgoing interface.""",
42+
"category": "network",
43+
},
44+
3: {
45+
'id': 3,
46+
"title": "What is brython",
47+
"body": """A Python 3 implementation for client-side web programming
48+
Without a doubt, you've seen a clock like this in demos of HTML5
49+
However, right click and view the source of this page...
50+
51+
It is not Javascript code! Instead, you will find Python code in a script of type "text/python".
52+
53+
Brython is designed to replace Javascript as the scripting language for the Web. As such, it is a Python 3 implementation (you can take it for a test drive through a web console), adapted to the HTML5 environment, that is to say with an interface to the DOM objects and events.
54+
55+
Speed of execution is similar to CPython for most operations.
56+
57+
The gallery highlights a few of the possibilities, from creating simple document elements to drag and drop and 3D navigation. A wiki lists some applications using Brython.
58+
You can also take a look at presentations made in various conferences.""",
59+
"category": "webdesign",
60+
},
61+
4: {
62+
'id': 4,
63+
"title": "What is Flutter",
64+
"body": """Flutter is an open-source UI software development kit created by Google. It is used to develop cross platform applications for Android, iOS, Linux, Mac, Windows, Google Fuchsia,[4] and the web from a single codebase.[5]
65+
66+
First described in 2015, Flutter was released in May 2017.[1]
67+
The first version of Flutter was known by the codename "Sky" and ran on the Android operating system. It was unveiled at the 2015 Dart developer summit[6] with the stated intent of being able to render consistently at 120 frames per second.[7] During the keynote of Google Developer Days in Shanghai in September 2018, Google announced Flutter Release Preview 2, which is the last big release before Flutter 1.0. On December 4th of that year, Flutter 1.0 was released at the Flutter Live event, denoting the first "stable" version of the Framework. On December 11, 2019, Flutter 1.12 was released at the Flutter Interactive event.[8]
68+
69+
On May 6, 2020, the Dart software development kit (SDK) in version 2.8 and the Flutter in version 1.17.0 were released, where support was added to the Metal API, improving performance on iOS devices (approximately 50%), new Material widgets, and new network tracking.
70+
71+
On March 3, 2021, Google released Flutter 2 during an online Flutter Engage event. This major update brought official support for web-based applications with new CanvasKit renderer and web specific widgets, early-access desktop application support for Windows, macOS, and Linux and improved Add-to-App APIs.[9] This release included sound null-safety, which caused many breaking changes and issues with many external packages, but the Flutter team included instructions to mitigate these changes as well.
72+
73+
On September 8th, 2021, the Dart SDK in version 2.14 and Flutter version 2.5 were released by Google. The update brought improvements to the Android Full-Screen mode and the latest version of Google's Material Design called Material You. Dart received two new updates, the newest lint conditions have been standardized and preset as the default conditions as well Dart for Apple Silicon is now stable.
74+
""",
75+
"category": "webdesign",
76+
},
77+
5: {
78+
'id': 5,
79+
"title": "What is Flask",
80+
"body": """Welcome to Flask’s documentation. Get started with Installation and then get an overview with the Quickstart. There is also a more detailed Tutorial that shows how to create a small but complete application with Flask. Common patterns are described in the Patterns for Flask section. The rest of the docs describe each component of Flask in detail, with a full reference in the API section.""",
81+
"category": "webdesign",
82+
},
83+
84+
85+
6: {
86+
87+
'id': 6,
88+
"title": "What is Dart",
89+
"body": """Dart is a client-optimized language for developing fast apps on any platform. Its goal is to offer the most productive programming language for multi-platform development, paired with a flexible execution runtime platform for app frameworks.
90+
91+
Languages are defined by their technical envelope — the choices made during development that shape the capabilities and strengths of a language. Dart is designed for a technical envelope that is particularly suited to client development, prioritizing both development (sub-second stateful hot reload) and high-quality production experiences across a wide variety of compilation targets (web, mobile, and desktop).
92+
93+
Dart also forms the foundation of Flutter. Dart provides the language and runtimes that power Flutter apps, but Dart also supports many core developer tasks like formatting, analyzing, and testing code.
94+
95+
Dart: The language
96+
The Dart language is type safe; it uses static type checking to ensure that a variable’s value always matches the variable’s static type. Sometimes, this is referred to as sound typing. Although types are mandatory, type annotations are optional because of type inference. The Dart typing system is also flexible, allowing the use of a dynamic type combined with runtime checks, which can be useful during experimentation or for code that needs to be especially dynamic.
97+
98+
Dart offers sound null safety, meaning that values can’t be null unless you say they can be. With sound null safety, Dart can protect you from null exceptions at runtime through static code analysis. Unlike many other null-safe languages, when Dart determines that a variable is non-nullable, that variable is always non-nullable. If you inspect your running code in the debugger, you’ll see that non-nullability is retained at runtime (hence sound null safety).
99+
100+
The following code sample showcases several Dart language features, including libraries, async calls, nullable and non-nullable types, arrow syntax, generators, streams, and getters. To find examples of using additional Dart features, see the samples page. To learn more about the language, take the Dart language tour.""",
101+
"category": "webdesign",
102+
103+
},
104+
105+
7: {
106+
'id': 7,
107+
'title': 'What is RIP',
108+
'body': """The Routing Information Protocol (RIP) is one of a family of IP Routing protocols, and is an Interior Gateway Protocol (IGP) designed to distribute routing information within an Autonomous System (AS).
109+
110+
RIP is a simple vector routing protocol with many existing implementations in the field. In a vector routing protocol, the routers exchange network reachability information with their nearest neighbors. In other words, the routers communicate to each other the sets of destinations ("address prefixes") that they can reach, and the next hop address to which data should be sent in order to reach those destinations. This contrasts with link-state IGPs; vectoring protocols exchange routes with one another, whereas link state routers exchange topology information, and calculate their own routes locally.
111+
112+
A vector routing protocol floods reachability information throughout all routers participating in the protocol, so that every router has a routing table containing the complete set of destinations known to the participating routers.""",
113+
'category': 'network',
114+
115+
},
116+
8: {
117+
'id': 8,
118+
'title': 'How to deploy a django project with ASGI',
119+
'body': """As well as WSGI, Django also supports deploying on ASGI, the emerging Python standard for asynchronous web servers and applications.
120+
121+
Django’s startproject management command sets up a default ASGI configuration for you, which you can tweak as needed for your project, and direct any ASGI-compliant application server to use.
122+
123+
Django includes getting-started documentation for the following ASGI servers:
124+
125+
How to use Django with Daphne
126+
How to use Django with Hypercorn
127+
How to use Django with Uvicorn
128+
The application object¶
129+
Like WSGI, ASGI has you supply an application callable which the application server uses to communicate with your code. It’s commonly provided as an object named application in a Python module accessible to the server.
130+
131+
The startproject command creates a file <project_name>/asgi.py that contains such an application callable.
132+
133+
It’s not used by the development server (runserver), but can be used by any ASGI server either in development or in production.
134+
135+
ASGI servers usually take the path to the application callable as a string; for most Django projects, this will look like myproject.asgi:application""",
136+
'category': 'webdesign',
137+
}
138+
}

fastapi-pro/schemas.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from pydantic import BaseModel
2+
3+
4+
class Post(BaseModel):
5+
id: int
6+
title: str
7+
body: str
8+
category: str
9+
10+
11+
class UpdatePost(BaseModel):
12+
title: str
13+
body: str
14+
category: str
15+
16+
class Config:
17+
orm_mode = True

0 commit comments

Comments
 (0)