-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
52 lines (38 loc) · 1.55 KB
/
main.py
File metadata and controls
52 lines (38 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
Main module for handling FastAPI endpoints and dependencies related to the blockchain.
"""
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
import blockchain as _blockchain
app = FastAPI()
class BlockData(BaseModel):
"""Model for block data input."""
data: str
def get_blockchain():
"""
Provides an instance of the Blockchain.
Checks if the blockchain is valid and raises an HTTPException if not.
"""
blockchain = _blockchain.Blockchain()
if not blockchain.is_chain_valid():
raise HTTPException(status_code=400, detail="The blockchain is invalid")
return blockchain
@app.post("/mine_block/")
def mine_block(
block_data: BlockData, blockchain: _blockchain.Blockchain = Depends(get_blockchain)
):
"""Mines a block with the provided data and returns the new block."""
return blockchain.mine_block(data=block_data.data)
@app.get("/blockchain/")
def get_blockchain_route(blockchain: _blockchain.Blockchain = Depends(get_blockchain)):
"""Returns the entire blockchain."""
return blockchain.chain
# pylint: disable=unused-argument
@app.get("/validate/")
def is_blockchain_valid(blockchain: _blockchain.Blockchain = Depends(get_blockchain)):
"""Checks if the blockchain is valid and returns a relevant message."""
return {"message": "The blockchain is valid."}
@app.get("/blockchain/last/")
def previous_block(blockchain: _blockchain.Blockchain = Depends(get_blockchain)):
"""Returns the last block in the blockchain."""
return blockchain.get_previous_block()