Update main.py
This commit is contained in:
parent
a3911bfc67
commit
f2af7408e8
@ -1,29 +1,36 @@
|
|||||||
from fastapi import FastAPI, Response
|
from fastapi import FastAPI
|
||||||
from playwright.async_api import async_playwright
|
from playwright.async_api import async_playwright, Browser
|
||||||
import os
|
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
from pydantic import BaseModel
|
|
||||||
|
|
||||||
class UrlModel(BaseModel):
|
class UrlModel(BaseModel):
|
||||||
url: str
|
url: str
|
||||||
|
|
||||||
@app.post("/html") # Kept as POST to accept body parameters
|
|
||||||
async def root(body: UrlModel): # Using Pydantic model for request body
|
|
||||||
async with async_playwright() as p:
|
|
||||||
browser = await p.chromium.launch()
|
|
||||||
|
|
||||||
context = await browser.new_context()
|
browser: Browser = None
|
||||||
page = await context.new_page()
|
|
||||||
|
|
||||||
await page.goto(body.url) # Adjusted to use the url from the request body model
|
|
||||||
page_content = await page.content() # Get the HTML content of the page
|
|
||||||
|
|
||||||
await context.close()
|
@app.on_event("startup")
|
||||||
await browser.close()
|
async def startup_event():
|
||||||
|
global browser
|
||||||
|
playwright = await async_playwright().start()
|
||||||
|
browser = await playwright.chromium.launch()
|
||||||
|
|
||||||
json_compatible_item_data = {"content": page_content}
|
|
||||||
return JSONResponse(content=json_compatible_item_data)
|
|
||||||
|
|
||||||
|
@app.on_event("shutdown")
|
||||||
|
async def shutdown_event():
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/html")
|
||||||
|
async def root(body: UrlModel):
|
||||||
|
context = await browser.new_context()
|
||||||
|
page = await context.new_page()
|
||||||
|
await page.goto(body.url)
|
||||||
|
page_content = await page.content()
|
||||||
|
await context.close()
|
||||||
|
json_compatible_item_data = {"content": page_content}
|
||||||
|
return JSONResponse(content=json_compatible_item_data)
|
||||||
|
Loading…
Reference in New Issue
Block a user