本文整理汇总了Python中formspree.forms.models.Form类的典型用法代码示例。如果您正苦于以下问题:Python Form类的具体用法?Python Form怎么用?Python Form使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Form类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rate_limiting_on_form_posts
def test_rate_limiting_on_form_posts(client, msend):
# confirm a form
client.post(
"/[email protected]xample.com",
headers={"referer": "http://somewhere.com"},
data={"name": "john"},
)
form = Form.get_with(host="somewhere.com", email="[email protected]")
form.confirmed = True
DB.session.add(form)
DB.session.commit()
# submit form many times
replies = []
for _ in range(1000):
r = client.post(
"/[email protected]",
headers={"referer": "http://somewhere.com"},
data={"name": "attacker"},
)
replies.append(r.status_code)
limit = int(settings.RATE_LIMIT.split(" ")[0])
# the number of submissions should not be more than the rate limit
form = Form.get_with(host="somewhere.com", email="[email protected]")
assert form.counter < limit
# should have gotten some 302 and then many 429 responses
assert replies.count(302) <= limit
assert replies.count(429) >= 900 - limit
示例2: test_a_confusing_case
def test_a_confusing_case(client, msend):
"""
Final boss.
"""
prepare()
try:
_, uf = create_user_and_form(client)
DB.session.add(Form(email=uf.email, confirmed=False, host="example.com"))
DB.session.add(Form(email=uf.email, confirmed=True, host="example.com/contact"))
DB.session.add(Form(email=uf.email, confirmed=True, host="www.example.com/"))
DB.session.commit()
assert Form.query.count() == 4
form = Form.get_with(email=uf.email, host="example.com/")
assert form
assert form.confirmed
assert form.host == "www.example.com/"
form2 = Form.get_with(email=uf.email, host="www.example.com")
assert form2
assert form2.confirmed
assert form.host == "www.example.com/"
contact = form.get_with(email=uf.email, host="www.example.com/contact/")
assert contact
assert contact.host == "example.com/contact"
assert form.id != contact.id
assert form.id == form2.id
r = client.post(
"/" + uf.email,
headers={"Referer": "http://example.com/"},
data={"name": "example"},
)
assert r.status_code == 302
assert "next" in r.location
r = client.post(
"/" + uf.email,
headers={"Referer": "www.example.com"},
data={"name": "example"},
)
assert r.status_code == 302
assert "next" in r.location
assert msend.call_count == 2
assert Form.query.count() == 4
form3 = Form.get_with(email=uf.email, host="example.com")
assert 2 == form.submissions.count()
assert form3.id == form2.id == form.id
finally:
revert()
示例3: google_call
def google_call(hashid):
form = Form.get_with(hashid=hashid)
session["ggl:form"] = form.hashid
hint = form.email
if not form.email.endswith("@gmail.com") and current_user.email.endswith(
"@gmail.com"
):
hint = current_user.email
flow = google_auth_oauthlib.flow.Flow.from_client_config(
settings.GOOGLE_CLIENT_CONFIG,
scopes=["https://www.googleapis.com/auth/drive.file"],
)
flow.redirect_uri = url_for(
"google_callback",
_external=True,
_scheme="https", # can't figure out how to get this to honor PREFERRED_URL_SCHEME
)
authorization_url, _ = flow.authorization_url(
access_type="offline",
login_hint=hint,
prompt="consent",
state=hashid,
include_granted_scopes="true",
)
return redirect(authorization_url)
示例4: confirm_email
def confirm_email(nonce):
"""
Confirmation emails point to this endpoint
It either rejects the confirmation or
flags associated email+host to be confirmed
"""
# get the form for this request
form = Form.confirm(nonce)
if not form:
return (
render_template(
"error.html",
title="Not a valid link",
text="Confirmation token not found.<br />Please check the link and try again.",
),
400,
)
else:
return render_template(
"forms/form_activated.html",
email=form.email,
host=form.host,
user=current_user,
)
示例5: test_backwards_none_confirmed
def test_backwards_none_confirmed(client, msend):
"""
This time no form is confirmed.
"""
prepare()
try:
for host in hosts:
f = Form(email=email, confirmed=False, host=host)
DB.session.add(f)
DB.session.commit()
for referer in hosts:
r = client.post(
"/" + email,
headers={"Referer": "http://" + referer},
data={"name": "example"},
)
assert r.status_code == 200
assert b"confirm" in r.get_data()
assert Form.get_with(email=email, host=referer).host == hosts[0]
assert Form.query.count() == len(hosts)
assert Form.query.filter_by(confirmed=True).count() == 0
assert Submission.query.count() == 0
finally:
revert()
示例6: test_upgraded_user_access
def test_upgraded_user_access(self):
httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json')
# register user
r = self.client.post('/register',
data={'email': '[email protected]',
'password': 'banana'}
)
# upgrade user manually
user = User.query.filter_by(email='[email protected]').first()
user.upgraded = True
DB.session.add(user)
DB.session.commit()
# create form
r = self.client.post('/forms',
headers={'Accept': 'application/json',
'Content-type': 'application/json'},
data=json.dumps({'email': '[email protected]'})
)
resp = json.loads(r.data)
form_endpoint = resp['random_like_string']
# manually confirm the form
form = Form.get_form_by_random_like_string(form_endpoint)
form.confirmed = True
DB.session.add(form)
DB.session.commit()
# submit form
r = self.client.post('/' + form_endpoint,
headers={'Referer': 'formspree.io'},
data={'name': 'bruce', 'message': 'hi!'}
)
# test submissions endpoint (/forms/<random_like_string>/)
r = self.client.get('/forms/' + form_endpoint + '/',
headers={'Accept': 'application/json'})
submissions = json.loads(r.data)['submissions']
self.assertEqual(len(submissions), 1)
self.assertEqual(submissions[0]['name'], 'bruce')
self.assertEqual(submissions[0]['message'], 'hi!')
# test submissions endpoint with the user downgraded
user.upgraded = False
DB.session.add(user)
DB.session.commit()
r = self.client.get('/forms/' + form_endpoint + '/')
self.assertEqual(r.status_code, 402) # it should fail
# test submissions endpoint without a logged user
self.client.get('/logout')
r = self.client.get('/forms/' + form_endpoint + '/')
self.assertEqual(r.status_code, 302) # it should return a redirect (via @user_required)
示例7: test_unconfirm_process
def test_unconfirm_process(client, msend):
# confirm some forms for the same email address
f1 = Form('[email protected]', 'testwebsite.com')
f1.confirmed = True
DB.session.add(f1)
f2 = Form('[email protected]', 'othertestwebsite.com')
f2.confirmed = True
DB.session.add(f2)
f3 = Form('[email protected]', 'anothertestwebsite.com')
f3.confirmed = True
DB.session.add(f3)
DB.session.commit()
# try a submission
r = client.post('/[email protected]',
headers = {'Referer': 'http://testwebsite.com'},
data={'name': 'carol'}
)
assert msend.called
request_unconfirm_url = url_for('request_unconfirm_form', form_id=f1.id, _external=True)
assert request_unconfirm_url in msend.call_args[1]['text']
msend.reset_mock()
# this should send a confirmation email
r = client.get(request_unconfirm_url)
assert r.status_code == 200
assert msend.called
unconfirm_url_with_digest = url_for(
'unconfirm_form',
form_id=f1.id,
digest=f1.unconfirm_digest(),
_external=True
)
assert unconfirm_url_with_digest in msend.call_args[1]['text']
msend.reset_mock()
# unconfirm this
r = client.get(unconfirm_url_with_digest)
assert f1.confirmed == False
# should show a page with the other options
assert r.status_code == 200
assert 'Select all' in r.data.decode('utf-8')
assert f2.host in r.data.decode('utf-8')
assert f3.host in r.data.decode('utf-8')
unconfirm_multiple_url = url_for('unconfirm_multiple')
assert unconfirm_multiple_url in r.data.decode('utf-8')
# we can use unconfirm_multiple to unconfirm f2
assert f2.confirmed == True
r = client.post(unconfirm_multiple_url, data={'form_ids': [f2.id]})
assert r.status_code == 200
assert 'Success' in r.data.decode('utf-8')
assert f2.confirmed == False
示例8: test_upgraded_user_access
def test_upgraded_user_access(self):
httpretty.register_uri(httpretty.POST, "https://api.sendgrid.com/api/mail.send.json")
# register user
r = self.client.post("/register", data={"email": "[email protected]", "password": "banana"})
# upgrade user manually
user = User.query.filter_by(email="[email protected]").first()
user.upgraded = True
DB.session.add(user)
DB.session.commit()
# create form
r = self.client.post(
"/forms",
headers={"Accept": "application/json", "Content-type": "application/json"},
data=json.dumps({"email": "[email protected]"}),
)
resp = json.loads(r.data)
form_endpoint = resp["hashid"]
# manually confirm the form
form = Form.get_with_hashid(form_endpoint)
form.confirmed = True
DB.session.add(form)
DB.session.commit()
# submit form
r = self.client.post(
"/" + form_endpoint, headers={"Referer": "formspree.io"}, data={"name": "bruce", "message": "hi!"}
)
# test submissions endpoint (/forms/<hashid>/)
r = self.client.get("/forms/" + form_endpoint + "/", headers={"Accept": "application/json"})
submissions = json.loads(r.data)["submissions"]
self.assertEqual(len(submissions), 1)
self.assertEqual(submissions[0]["name"], "bruce")
self.assertEqual(submissions[0]["message"], "hi!")
# test submissions endpoint with the user downgraded
user.upgraded = False
DB.session.add(user)
DB.session.commit()
r = self.client.get("/forms/" + form_endpoint + "/")
self.assertEqual(r.status_code, 402) # it should fail
# test submissions endpoint without a logged user
self.client.get("/logout")
r = self.client.get("/forms/" + form_endpoint + "/")
self.assertEqual(r.status_code, 302) # it should return a redirect (via @user_required)
示例9: google_callback
def google_callback():
hashid = session["ggl:form"]
del session["ggl:form"]
if hashid != request.args.get("state"):
return script_error("oauth-failed")
form = Form.get_with(hashid=hashid)
flow = google_auth_oauthlib.flow.Flow.from_client_config(
settings.GOOGLE_CLIENT_CONFIG,
state=hashid,
scopes=["https://www.googleapis.com/auth/drive.file"],
)
flow.redirect_uri = url_for("google_callback", _external=True, _scheme="https")
flow.fetch_token(authorization_response=request.url.replace("http://", "https://"))
plugin = Plugin(form_id=form.id, kind=PluginKind.google_sheets)
plugin.access_token = json.dumps(
{
"token": flow.credentials.token,
"refresh_token": flow.credentials.refresh_token,
"token_uri": flow.credentials.token_uri,
"id_token": flow.credentials.id_token,
"client_id": flow.credentials.client_id,
"client_secret": flow.credentials.client_secret,
}
)
spreadsheet_title = (
form.name
if form.name
else f"{settings.SERVICE_NAME} submissions for {form.hashid}"
)[:128]
google_creds = json.loads(plugin.access_token)
credentials = google.oauth2.credentials.Credentials(**google_creds)
spreadsheet_id, worksheet_id = create_google_sheet(
form, spreadsheet_title, credentials
)
plugin.plugin_data = {
"spreadsheet_id": spreadsheet_id,
"worksheet_id": worksheet_id,
}
DB.session.add(plugin)
DB.session.commit()
return script_data({"spreadsheet_id": spreadsheet_id})
示例10: validate_user_form
def validate_user_form(hashid):
"""
Gets a form from a hashid, created on the dashboard.
Checks to make sure the submission can be accepted by this form.
"""
form = Form.get_with(hashid=hashid)
if not form:
raise SubmitFormError(errors.bad_hashid_error(hashid))
if form.disabled:
raise SubmitFormError(errors.disabled_error())
return form
示例11: mailchimp_callback
def mailchimp_callback():
error = request.args.get("error")
if error:
return script_error(error if error == "access-denied" else "oauth-failed")
hashid = session["mcp:form"]
del session["mcp:form"]
if hashid != request.args.get("state"):
return script_error("oauth-failed")
code = request.args.get("code")
r = requests.post(
"https://login.mailchimp.com/oauth2/token",
data={
"grant_type": "authorization_code",
"client_id": settings.MAILCHIMP_CLIENT_ID,
"client_secret": settings.MAILCHIMP_CLIENT_SECRET,
"code": code,
"redirect_uri": url_for(
"mailchimp_callback", _external=True, _scheme="https"
),
},
)
if not r.ok:
return script_error("oauth-failed")
data = r.json()
form = Form.get_with(hashid=hashid)
plugin = Plugin(form_id=form.id, kind=PluginKind.mailchimp)
r = requests.get(
"https://login.mailchimp.com/oauth2/metadata",
headers={"Authorization": "OAuth " + data["access_token"]},
)
if not r.ok:
return script_error("oauth-failed")
meta = r.json()
plugin.access_token = data["access_token"]
plugin.plugin_data = {"api_endpoint": meta["api_endpoint"], "dc": meta["dc"]}
plugin.enabled = False
DB.session.add(plugin)
DB.session.commit()
return script_data({"ok": True})
示例12: slack_call
def slack_call(hashid):
form = Form.get_with(hashid=hashid)
session["slk:form"] = form.hashid
return redirect(
"https://slack.com/oauth/authorize?"
+ urlencode(
{
"client_id": settings.SLACK_CLIENT_ID,
"scope": "incoming-webhook",
"redirect_uri": url_for(
"slack_callback", _external=True, _scheme="https"
),
"state": form.hashid,
}
)
)
示例13: confirm_email
def confirm_email(nonce):
'''
Confirmation emails point to this endpoint
It either rejects the confirmation or
flags associated email+host to be confirmed
'''
# get the form for this request
form = Form.confirm(nonce)
if not form:
return render_template('error.html',
title='Not a valid link',
text='Confirmation token not found.<br />Please check the link and try again.'), 400
else:
return render_template('forms/email_confirmed.html', email=form.email, host=form.host)
示例14: mailchimp_call
def mailchimp_call(hashid):
form = Form.get_with(hashid=hashid)
session["mcp:form"] = form.hashid
return redirect(
"https://login.mailchimp.com/oauth2/authorize?"
+ urlencode(
{
"response_type": "code",
"client_id": settings.MAILCHIMP_CLIENT_ID,
"redirect_uri": url_for(
"mailchimp_callback", _external=True, _scheme="https"
),
"state": form.hashid,
}
)
)
示例15: export_submissions
def export_submissions(hashid, format=None):
if not current_user.has_feature("dashboard"):
return jsonify({"error": "Please upgrade your account."}), 402
form = Form.get_with(hashid=hashid)
if not form.controlled_by(current_user):
return abort(401)
submissions, fields = form.submissions_with_fields(with_ids=False)
if format == "json":
return Response(
json.dumps(
{
"host": form.host,
"email": form.email,
"fields": fields,
"submissions": submissions,
},
sort_keys=True,
indent=2,
),
mimetype="application/json",
headers={
"Content-Disposition": "attachment; filename=form-%s-submissions-%s.json"
% (hashid, datetime.datetime.now().isoformat().split(".")[0])
},
)
elif format == "csv":
out = io.BytesIO()
w = csv.DictWriter(out, fieldnames=fields, encoding="utf-8")
w.writeheader()
for sub in submissions:
w.writerow(sub)
return Response(
out.getvalue(),
mimetype="text/csv",
headers={
"Content-Disposition": "attachment; filename=form-%s-submissions-%s.csv"
% (hashid, datetime.datetime.now().isoformat().split(".")[0])
},
)