forked from k1m190r/evangeler2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
183 lines (152 loc) · 5.3 KB
/
main.py
File metadata and controls
183 lines (152 loc) · 5.3 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import json
import os
from pathlib import Path
from fastapi import FastAPI, Form
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.responses import HTMLResponse
templates = Jinja2Templates(directory=".")
app = FastAPI(
openapi_url="/static/openapi.json",
docs_url="/swagger-docs",
redoc_url="/redoc",
title="Evangeler affliate marketing",
description="Evangeler",
# root_path="https://api.text-generator.io",
version="1",
)
app.add_middleware(GZipMiddleware, minimum_size=1000)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory="static"), name="static")
# rollbar_add_to(app) # rollbar doesnt work anymore?
# JINJA_ENVIRONMENT = jinja2.Environment(
# loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
# # extensions=['jinja2.ext.autoescape'],
# # autoescape=True
# )
current_dir = Path(__file__).parent
debug = (
os.environ.get("SERVER_SOFTWARE", "").startswith("Development")
or os.environ.get("IS_DEVELOP", "") == 1
or Path(current_dir / "models/debug.env").exists()
)
static_url = "/static"
# load json
if not debug:
static_url = "https://static.netwrck.com/static"
with open('affiliates.json') as f:
affiliates = json.load(f)
with open('affiliate_details.json') as f:
affiliate_details = json.load(f)
details_lookup = {d['slug']: d for d in affiliate_details}
SUBMISSION_FILE = Path('affiliate_submissions.json')
def load_submissions():
if SUBMISSION_FILE.exists():
try:
return json.loads(SUBMISSION_FILE.read_text())
except Exception:
return []
return []
def save_submission(entry: dict):
submissions = load_submissions()
submissions.append(entry)
SUBMISSION_FILE.write_text(json.dumps(submissions, indent=2))
import re
for site in affiliates:
slug = re.sub(r'[^a-z0-9]+', '-', site['brand'].lower()).strip('-')
site['slug'] = slug
@app.get("/")
async def home(request: Request):
return templates.TemplateResponse("templates/index.jinja2",
{"request": request, "affiliates": affiliates, "static_url": static_url})
@app.get("/affiliate/{slug}")
async def affiliate_detail(slug: str, request: Request):
detail = details_lookup.get(slug)
if not detail:
return templates.TemplateResponse("templates/not_found.jinja2", {"request": request}, status_code=404)
return templates.TemplateResponse(
"templates/detail.jinja2",
{"request": request, "detail": detail, "static_url": static_url},
)
@app.get("/sitemap.xml")
async def sitemap():
urls = [f"https://evangeler.com/affiliate/{d['slug']}" for d in affiliate_details]
xml_parts = ["<?xml version='1.0' encoding='UTF-8'?>", "<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>"]
for url in urls:
xml_parts.append(" <url><loc>%s</loc></url>" % url)
xml_parts.append("</urlset>")
return "\n".join(xml_parts)
@app.get("/robots.txt")
async def robots():
return "User-agent: *\nAllow: /"
@app.get("/search")
async def search(request: Request, query: str = ""):
q = query.lower()
results = []
if q:
for site in affiliates:
if q in site['brand'].lower() or q in site['description'].lower() or q in site['keywords'].lower():
results.append(site)
return templates.TemplateResponse(
"templates/search.jinja2",
{"request": request, "results": results, "query": query, "static_url": static_url},
)
@app.get("/submit")
async def submit_form(request: Request):
return templates.TemplateResponse(
"templates/submit.jinja2",
{"request": request, "error": ""},
)
@app.post("/submit")
async def submit_affiliate(
request: Request,
brand: str = Form(...),
description: str = Form(...),
website: str = Form(...),
keywords: str = Form(""),
commission: str = Form(""),
email: str = Form(""),
nickname: str = Form(""),
):
if not website.startswith("http"):
return templates.TemplateResponse(
"templates/submit.jinja2",
{"request": request, "error": "Invalid website URL."},
status_code=400,
)
slug = re.sub(r"[^a-z0-9]+", "-", brand.lower()).strip("-")
if nickname:
# likely bot submission, ignore but pretend success
return templates.TemplateResponse(
"templates/submit_success.jinja2", {"request": request}
)
entry = {
"brand": brand,
"slug": slug,
"description": description,
"website": website,
"keywords": keywords,
"commission": commission,
"email": email,
}
save_submission(entry)
return templates.TemplateResponse(
"templates/submit_success.jinja2",
{"request": request},
)
@app.get("/submissions")
async def view_submissions(request: Request):
submissions = load_submissions()
return templates.TemplateResponse(
"templates/submissions.jinja2",
{"request": request, "submissions": submissions},
)