-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
261 lines (224 loc) · 7.5 KB
/
main.py
File metadata and controls
261 lines (224 loc) · 7.5 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""FastAPI example using Forminit SDK."""
import os
from contextlib import asynccontextmanager
from typing import Optional
from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from forminit import AsyncForminitClient
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage application lifespan."""
# Startup
yield
# Shutdown
app = FastAPI(title="Forminit FastAPI Example", lifespan=lifespan)
# HTML template for the contact form
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>Contact Form - FastAPI Example</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
textarea {
height: 100px;
}
button {
background: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
.success {
color: green;
margin-top: 10px;
}
.error {
color: red;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Contact Us</h1>
<form id="contactForm">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="fi-sender-fullName" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="fi-sender-email" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea id="message" name="fi-text-message" required></textarea>
</div>
<button type="submit">Send Message</button>
<div id="status"></div>
</form>
<script>
document.getElementById('contactForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const statusDiv = document.getElementById('status');
statusDiv.textContent = 'Sending...';
statusDiv.className = '';
try {
const response = await fetch('/submit', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
statusDiv.textContent = 'Message sent successfully!';
statusDiv.className = 'success';
e.target.reset();
} else {
statusDiv.textContent = 'Error: ' + (result.message || 'Unknown error');
statusDiv.className = 'error';
}
} catch (error) {
statusDiv.textContent = 'Error: ' + error.message;
statusDiv.className = 'error';
}
});
</script>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse)
async def index():
"""Render the contact form."""
return HTML_TEMPLATE
@app.post("/submit")
async def submit(
request: Request,
fi_sender_fullName: str = Form(...),
fi_sender_email: str = Form(...),
fi_text_message: str = Form(...),
):
"""Handle form submission using async client."""
# Extract client information from request headers for accurate tracking
# Note: Use X-Forwarded-For when behind proxies, load balancers, or CDNs
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
# X-Forwarded-For can contain multiple IPs, get the first one (client IP)
client_ip = forwarded_for.split(",")[0].strip()
else:
client_ip = request.client.host if request.client else "127.0.0.1"
user_agent = request.headers.get("User-Agent", "unknown")
referer = request.headers.get("Referer")
# Get API key
api_key = os.environ.get("FORMINIT_API_KEY")
if not api_key:
raise HTTPException(status_code=500, detail="API key not configured")
# Build form data
form_data = {
"fi-sender-fullName": fi_sender_fullName,
"fi-sender-email": fi_sender_email,
"fi-text-message": fi_text_message,
}
# Submit using async client
async with AsyncForminitClient(api_key=api_key) as client:
client.set_user_info(
ip=client_ip,
user_agent=user_agent,
referer=referer,
)
result = await client.submit(
form_id=os.environ.get("FORMINIT_FORM_ID", "your-form-id"),
data=form_data,
)
if "error" in result:
raise HTTPException(
status_code=result["error"].get("code", 400),
detail=result["error"].get("message", "Submission failed"),
)
return {"success": True, "submissionId": result["data"]["hashId"]}
class DirectSubmission(BaseModel):
"""Direct submission request model."""
formId: Optional[str] = None
email: str
firstName: Optional[str] = None
lastName: Optional[str] = None
message: str
tracking: Optional[dict[str, str]] = None
@app.post("/api/direct-submit")
async def direct_submit(request: Request, submission: DirectSubmission):
"""Example of direct JSON submission with structured blocks."""
api_key = os.environ.get("FORMINIT_API_KEY")
if not api_key:
raise HTTPException(status_code=500, detail="API key not configured")
# Extract client information from request headers for accurate tracking
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
client_ip = forwarded_for.split(",")[0].strip()
else:
client_ip = request.client.host if request.client else "127.0.0.1"
user_agent = request.headers.get("User-Agent", "unknown")
referer = request.headers.get("Referer")
# Build structured submission
form_data = {
"blocks": [
{
"type": "sender",
"properties": {
"email": submission.email,
"firstName": submission.firstName or "",
"lastName": submission.lastName or "",
},
},
{"type": "text", "name": "message", "value": submission.message},
]
}
async with AsyncForminitClient(api_key=api_key) as client:
client.set_user_info(
ip=client_ip,
user_agent=user_agent,
referer=referer,
)
result = await client.submit(
form_id=submission.formId or os.environ.get("FORMINIT_FORM_ID", "your-form-id"),
data=form_data,
tracking=submission.tracking,
)
if "error" in result:
raise HTTPException(
status_code=result["error"].get("code", 400),
detail=result["error"],
)
return {
"success": True,
"data": result["data"],
"redirectUrl": result.get("redirectUrl"),
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)