Skip to content

Instantly share code, notes, and snippets.

@shane0
Last active February 14, 2020 08:53
Show Gist options
  • Save shane0/6f73f98c0ac64d85e986a35ef52c4c22 to your computer and use it in GitHub Desktop.
Save shane0/6f73f98c0ac64d85e986a35ef52c4c22 to your computer and use it in GitHub Desktop.
flask-flatpages search
class SearchFlatsForm(Form):
"""search flat pages"""
searchterm = StringField('searchterm',
validators=[DataRequired(),
Length(min=3, max=30),
])
{% extends "layout.html" %}
{% block content %}
<!-- Start your project here-->
<h2>Search</h2>
<hr>
<form id="SearchFlatsForm" class="form" method="POST" action="{{ url_for('flat.searchflats') }}" role="form">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="form-group">
{{form.searchterm(placeholder="enter search term", class_="form-control")}}
</div>
<p><input class="btn btn-default btn-submit" type="submit" value="search"></p>
</form>
<hr>
<h4>output</h4>
<table class="table">
<thead>
<th>page</th>
<th>match</th>
</thead>
{% for key, value in matchcontent.items() %}
<tr>
<td>
<a class="btn btn-link" href="/flatpages/{{key}}">{{key}}</a>
</td>
<td>
{{ value }}
</td>
</tr>
{% endfor %}
</table>
<!-- /Start your project here-->
{% endblock %}
@blueprint.route('/search/', methods=['GET','POST'])
@login_required
def searchflats():
# thisdir = os.path.abspath(os.path.dirname(__file__))
# pagedir = os.path.abspath(os.path.join(thisdir, os.pardir, 'pages'))
# location = pagedir
# location = FLATPAGES_ROOT
# above didn't work hard coding path for now
location = 'C:/Users/yourusername/flaskappdir/pages/' # yuk i'm on win32
matches = {}
matchcontent = {}
form = SearchFlatsForm(request.form, csrf_enabled=False)
if form.validate_on_submit():
searchterm = form.searchterm.data
for dir_path, dirs, file_names in os.walk(location):
for file_name in file_names:
fullpath = os.path.join(dir_path, file_name)
with open(fullpath,encoding='utf-8',errors='ignore') as f:
print(fullpath)
content = f.readlines()
for c in content:
if searchterm in c:
fixedpath = fullpath.replace('C:/Users/yourusername/flaskappdir/pages/', '')
fixedpath = fixedpath.replace('.md','')
matchcontent[fixedpath] = c
matches[file_name] = c
return render_template('flatpages/search.html', form=form, matches=matches, pages=pages,matchcontent=matchcontent)
else:
flash_errors(form)
return render_template('flatpages/search.html', form=form, matches=matches, pages=pages,matchcontent=matchcontent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment