Last active
June 11, 2019 06:25
-
-
Save kaushikgandhi/15f0600475d9b06333b67f66269f7bab to your computer and use it in GitHub Desktop.
How to perform a jinja2 test for your flask app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Purpose of this code is to test your flask app for jinja2 rendering issue | |
#If you have a large database and your jinja2 code can break due to uneven db rows, this will serve the purpose | |
from flask import Flask, request, session, g, redirect, url_for, \ | |
abort, render_template, flash,send_from_directory | |
import MySQLdb,json | |
import datetime | |
app = Flask(__name__, static_url_path='/static') | |
app.config.from_object(__name__) | |
app.wsgi_app = ProxyFix(app.wsgi_app) | |
##configuration | |
DATABASE = '#YourDBName' | |
DB_SERVER = 'localhost' | |
DEBUG = True | |
USERNAME = 'root' | |
PASSWORD = '#password' | |
import datetime | |
import urllib | |
#Mysql Connection Declaration | |
class SQLconnection: | |
def init(self): | |
self.db = MySQLdb.connect(DB_SERVER,USERNAME,PASSWORD,DATABASE) | |
self.db.autocommit(True) | |
self.db.ping(True) | |
self.cursor = self.db.cursor() | |
def re_connect(self): | |
self.db = MySQLdb.connect(DB_SERVER,USERNAME,PASSWORD,DATABASE) | |
self.db.autocommit(True) | |
self.db.ping(True) | |
self.cursor = self.db.cursor() | |
def close_connection(self): | |
self.cursor.close() | |
self.db.close() | |
_connection = SQLconnection() | |
_connection.init() | |
error_file = open('error.txt','w+') | |
import jinja2 | |
def render_any_page(args if needed): | |
##You render code copy paste from server.py | |
try: | |
templateLoader = jinja2.FileSystemLoader(searchpath="./") | |
templateEnv = jinja2.Environment(loader=templateLoader) | |
TEMPLATE_FILE = "templates/distance_page_test.html" | |
template = templateEnv.get_template(TEMPLATE_FILE) | |
outputText = template.render(all_args_you_need_to_render_your_template_same_as_server_code) # this is where to put args to the template renderer | |
except Exception as e: | |
print e | |
print 'error in row',row_id ##Row _id is the row in db you want to fix | |
error_file.write(str(row_id)+'\n') #row_id | |
return 0 | |
print 'no_error' | |
##call render_page() for each row in your db to perform a site wide test for your jinja2 operation | |
## Downfall for this code is it takes a lot of time. You can launch a multithread operation for improving it's performance. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment