Salahin commited on
Commit
3235ebd
·
1 Parent(s): cb2f158

Rearrange File Structure

Browse files
Files changed (4) hide show
  1. app/main.py +9 -17
  2. app/routers/random.py +27 -49
  3. app/schemas/user.py +6 -0
  4. app/utils/utils.py +46 -3
app/main.py CHANGED
@@ -1,26 +1,18 @@
1
- from fastapi import FastAPI
2
- from routers.random import random_router
3
 
4
  app = FastAPI()
5
- app.include_router(random_router)
6
 
7
  @app.get("/")
8
- def get_home() -> dict:
9
  """Return the API home page with available routes."""
10
- routes = {
11
- "/": "Description of the api",
12
- "/random": "Get a random float between 0 and 1.",
13
- "/random/int": "Get a random integer",
14
- "/random/range/{left}/{right}": "Get a random integer within the specified range.",
15
- "/random/char": "Get a random ASCII character.",
16
- "/random/coinflip": "Simulate a coin toss and get the result.",
17
- "/random/choice/{options}": "Select a random option from the given list.",
18
- "/random/color": "Select a random hex color.",
19
- "/random/user": "Generate a random user with name, email, and password.",
20
- "/random/password/{length}": "Generate a random password of a specified length.",
21
- }
22
  meta = {
23
  "api_version": "1.0",
24
  "docs": "https://github.com/MahirSalahin/random_api"
25
  }
26
- return {"routes": routes, "meta": meta}
 
1
+ from fastapi import FastAPI, Request, routing
2
+ from routers.random import router as randoom_router
3
 
4
  app = FastAPI()
5
+ app.include_router(randoom_router)
6
 
7
  @app.get("/")
8
+ def get_home(request: Request) -> dict:
9
  """Return the API home page with available routes."""
10
+ routes = {}
11
+ for route in request.app.routes:
12
+ if isinstance(route, routing.APIRoute):
13
+ routes[route.path] = route.name
 
 
 
 
 
 
 
 
14
  meta = {
15
  "api_version": "1.0",
16
  "docs": "https://github.com/MahirSalahin/random_api"
17
  }
18
+ return {"routes": routes, "meta": meta}
app/routers/random.py CHANGED
@@ -1,90 +1,68 @@
1
  from fastapi import APIRouter, HTTPException
2
- import random
3
  import json
4
- import secrets
5
  import string
6
- import faker
7
  from utils.utils import *
8
 
9
 
10
- random_router = APIRouter()
11
 
12
- @random_router.get("/random")
 
13
  def get_root() -> dict:
14
  """Return a random float between 0 and 1."""
15
- return {"float": random.random()}
16
 
17
 
18
- @random_router.get("/random/int")
19
  def get_random_int() -> dict:
20
  """Return a random integer."""
21
- return {"int": generate_random_int()}
22
 
23
 
24
- @random_router.get("/random/range/{left}/{right}")
25
  def get_random_in_range(left: int, right: int) -> dict:
26
  """Return a random integer within the given range."""
27
  if left > right:
28
  raise HTTPException(status_code=400, detail="Invalid range")
29
- return {"int": generate_random_int(left, right)}
30
 
31
 
32
- @random_router.get("/random/char")
33
  def generate_random_char() -> dict:
34
  """Get a random ASCII character."""
35
- return {"char": random.choice(string.ascii_letters)}
36
 
37
 
38
- @random_router.get("/random/coinflip")
39
  def toss_coin() -> dict:
40
  """Simulate a coin toss and return the result."""
41
- return {"result": random.choice(["Heads", "Tails"])}
42
 
43
 
44
- @random_router.get("/random/choice/{options}")
45
- def select_randomly(options: str) -> dict:
46
  """Select a random option from the given list."""
47
  options_list = json.loads(options)
48
  if not options_list:
49
  raise HTTPException(status_code=400, detail="Invalid options")
50
- return {"selected": random.choice(options_list)}
51
 
52
 
53
- @random_router.get("/random/color")
54
  def get_color() -> dict:
55
  """Select a random hex color."""
56
- hex_colors = [
57
- "#" + "".join([random.choice('0123456789ABCDEF') for _ in range(6)])]
58
- return {"color": hex_colors[0]}
59
 
60
 
61
- @random_router.get("/random/user")
62
- def generate_user() -> dict:
63
  """Generate a random user with name, email, and password."""
64
- fake = faker.Faker()
65
- name = fake.name()
66
- first_name, last_name = name.split()[0].lower(), name.split()[-1].lower()
67
- nums = ''
68
- for _ in range(random.randint(0, 4)):
69
- nums += str(random.randint(0, 9))
70
- email = random.choice(
71
- [f"{first_name}.{last_name}@{fake.free_email_domain()}",
72
- f"{first_name}.{last_name}{nums}@{fake.free_email_domain()}",
73
- f"{nums}{first_name}@{fake.free_email_domain()}",
74
- f"{first_name}{nums}@{fake.free_email_domain()}",
75
- f"{last_name}{nums}@{fake.free_email_domain()}",
76
- ])
77
- user = {
78
- "name": name,
79
- "email": email,
80
- "password": fake.password()
81
- }
82
- return user
83
-
84
-
85
- @random_router.get("/random/password/{length}")
86
- def generate_password(length: int) -> dict:
87
  """Generate a random password of a specified length."""
88
- alphabet = string.ascii_letters + string.digits + string.punctuation
89
- password = "".join(secrets.choice(alphabet) for _ in range(length))
90
- return {"password": password}
 
1
  from fastapi import APIRouter, HTTPException
 
2
  import json
 
3
  import string
 
4
  from utils.utils import *
5
 
6
 
7
+ router = APIRouter(prefix="/random")
8
 
9
+
10
+ @router.get("/")
11
  def get_root() -> dict:
12
  """Return a random float between 0 and 1."""
13
+ return {"float": random_float()}
14
 
15
 
16
+ @router.get("/int")
17
  def get_random_int() -> dict:
18
  """Return a random integer."""
19
+ return {"int": random_int()}
20
 
21
 
22
+ @router.get("/{left}/{right}")
23
  def get_random_in_range(left: int, right: int) -> dict:
24
  """Return a random integer within the given range."""
25
  if left > right:
26
  raise HTTPException(status_code=400, detail="Invalid range")
27
+ return {"int": random_int(left, right)}
28
 
29
 
30
+ @router.get("/char")
31
  def generate_random_char() -> dict:
32
  """Get a random ASCII character."""
33
+ return {"char": random_choice(string.ascii_letters)}
34
 
35
 
36
+ @router.get("/coinflip")
37
  def toss_coin() -> dict:
38
  """Simulate a coin toss and return the result."""
39
+ return {"result": random_choice(["Heads", "Tails"])}
40
 
41
 
42
+ @router.get("/{options}")
43
+ def get_random_option(options: str) -> dict:
44
  """Select a random option from the given list."""
45
  options_list = json.loads(options)
46
  if not options_list:
47
  raise HTTPException(status_code=400, detail="Invalid options")
48
+ return {"selected": random_choice(options_list)}
49
 
50
 
51
+ @router.get("/color")
52
  def get_color() -> dict:
53
  """Select a random hex color."""
54
+ hex_color = "#" + \
55
+ "".join([random_choice('0123456789ABCDEF') for _ in range(6)])
56
+ return {"color": hex_color}
57
 
58
 
59
+ @router.get("/user")
60
+ def get_user() -> User:
61
  """Generate a random user with name, email, and password."""
62
+ return random_user()
63
+
64
+
65
+ @router.get("/password/{length}")
66
+ def get_password(length: int) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  """Generate a random password of a specified length."""
68
+ return {"password": random_password(length=length)}
 
 
app/schemas/user.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+ class User(BaseModel):
4
+ name: str = None
5
+ email: str = None
6
+ password: str = None
app/utils/utils.py CHANGED
@@ -1,4 +1,47 @@
1
- from random import randint
2
- def generate_random_int(left: int = 0, right: int = 10**100) -> int:
 
 
 
 
3
  """Generate a random integer within the given range."""
4
- return randint(left, right)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from random import randint, random, choice
2
+ from schemas.user import User
3
+ from faker import Faker
4
+
5
+
6
+ def random_int(l: int = 0, r: int = 10**3) -> int:
7
  """Generate a random integer within the given range."""
8
+ return randint(l, r)
9
+
10
+ def random_float()->float:
11
+ """Generate a random float number."""
12
+ return random()
13
+ def random_choice(options: list):
14
+ """Generate a random choice from a list of options."""
15
+ return choice(options)
16
+
17
+
18
+ def random_password(length=8) -> str:
19
+ """Generate a random password of given length"""
20
+ return Faker().password(length=length)
21
+
22
+
23
+ def random_email(user_name: str = Faker().name()) -> str:
24
+ """Generate a random email address"""
25
+ first_name, last_name = user_name.split(
26
+ )[0].lower(), user_name.split()[-1].lower()
27
+
28
+ random_nums = ''.join(str(random_int(r=9))
29
+ for _ in range(random_int(r=4)))
30
+ email_domain = Faker().free_email_domain()
31
+
32
+ return choice(
33
+ [f"{first_name}.{last_name}@{email_domain}",
34
+ f"{last_name}.{first_name}@{email_domain}",
35
+ f"{first_name}.{last_name}{random_nums}@{email_domain}",
36
+ f"{random_nums}{first_name}@{email_domain}",
37
+ f"{first_name}{random_nums}@{email_domain}",
38
+ f"{last_name}{random_nums}@{email_domain}",
39
+ ])
40
+
41
+
42
+ def random_user() -> User:
43
+ user = User()
44
+ user.name = Faker().name()
45
+ user.password = random_password()
46
+ user.email = random_email(user_name=user.name)
47
+ return user