python - Invalid RegEx Entered by User in Django Form Causes 500 Server Error -


i have simple django search form set in web application, users can search particular words in arabic corpus. users can search 1 of 3 way: 'exact' (the word it's typed), 'stem' (which brings inflected forms of lemma entered), , 'regex' (where can more complex searches regular expression).

the problem i'm having is, if user submits invalid regex, instead of giving them validation error or empty results, triggers 500 server error. imagine confusing. below traceback such , error, caused searching regex unbalanced parenthesis: ha((.*(?!al))

is there anyway catch kind of error, or make more user-friendly? (i've included code form below.)

thank you.

class concordanceform(forms.form):     searchterm = forms.charfield(max_length=100, required=true)     search_type = forms.choicefield(widget=radioselect(),               choices= ([('string', 'exact'), ('lemma', 'stem'), ('regex', 'regex') ]),              required=true )   def concord_test(request):       if request.method == 'post':          form = concordanceform(request.post)         if form.is_valid():              searchterm = form.cleaned_data['searchterm'].encode('utf-8')             search_type = form.cleaned_data['search_type']             context, texts_len, results_len = make_concordance(searchterm, search_type)             return render_to_response('corpus/concord.html', locals())     else:         form = concordanceform()     return render_to_response('corpus/search_test.html',                                {'form': form}, context_instance=requestcontext(request))    <p style=" font-weight:bold;">search word in corpus:</p> <form action="/search_test/" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="submit" /> </form> 

traceback (most recent call last):

  file "/home/larapsodia/webapps/django/lib/python2.6/django/core/handlers/base.py", line 100, in get_response     response = callback(request, *callback_args, **callback_kwargs)    file "/home/larapsodia/webapps/django/tunisiya2/corpus/views.py", line 154, in concord_test     context, texts_len, results_len = make_concordance(searchterm, search_type)    file "/home/larapsodia/webapps/django/tunisiya2/corpus/views.py", line 91, in make_concordance     p = re.compile(r'\b' + searchterm + r'__') # initial position in word_pos_lemma string    file "/usr/local/lib/python2.6/re.py", line 190, in compile     return _compile(pattern, flags)    file "/usr/local/lib/python2.6/re.py", line 245, in _compile     raise error, v # invalid expression  error: unbalanced parenthesis   <wsgirequest get:<querydict: {}>, post:<querydict: {u'searchterm': [u'ha((.*(?!al))'], u'search_type': [u'regex'], u'csrfmiddlewaretoken': [u'c9a6cad4a0761580f5e351e9e534e028']}>, cookies:{'__utma': '58037167.1544119768.1401037185.1401381302.1401384825.14',  '__utmb': '58037167.10.10.1401384825',  '__utmc': '58037167',  '__utmz': '58037167.1401037185.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',  'csrftoken': 'c9a6cad4a0761580f5e351e9e534e028',  'sessionid': '8d5b0b8730ccce0860b687b4c7ec1fdb'}, meta:{'content_length': '109',  'content_type': 'application/x-www-form-urlencoded',  'csrf_cookie': 'c9a6cad4a0761580f5e351e9e534e028',  'document_root': '/usr/local/apache2/htdocs',  'gateway_interface': 'cgi/1.1',  'http_accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',  'http_accept_encoding': 'gzip,deflate,sdch',  'http_accept_language': 'en-us,en;q=0.8,ar;q=0.6',  'http_cache_control': 'max-age=0',  'http_connection': 'close',  'http_cookie': 'sessionid=8d5b0b8730ccce0860b687b4c7ec1fdb; csrftoken=c9a6cad4a0761580f5e351e9e534e028; __utma=58037167.1544119768.1401037185.1401381302.1401384825.14; __utmb=58037167.10.10.1401384825; __utmc=58037167; __utmz=58037167.1401037185.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',  'http_forwarded_request_uri': '/search_test/',  'http_host': 'www.tunisiya.org',  'http_https': 'off',  'http_http_x_forwarded_proto': 'http',  'http_origin': 'http://www.tunisiya.org',  'http_referer': 'http://www.tunisiya.org/search_test/',  'http_user_agent': 'mozilla/5.0 (macintosh; intel mac os x 10_9_3) applewebkit/537.36 (khtml, gecko) chrome/35.0.1916.114 safari/537.36',  'http_x_forwarded_for': '68.9.41.110',  'http_x_forwarded_host': 'www.tunisiya.org',  'http_x_forwarded_proto': 'http',  'http_x_forwarded_server': 'www.tunisiya.org',  'http_x_forwarded_ssl': 'off',  'path_info': u'/search_test/',  'path_translated': '/home/larapsodia/webapps/django/tunisiya2.wsgi/search_test/',  'query_string': '',  'remote_addr': '127.0.0.1',  'remote_port': '37086',  'request_method': 'post',  'request_uri': '/search_test/',  'script_filename': '/home/larapsodia/webapps/django/tunisiya2.wsgi',  'script_name': u'',  'server_addr': '127.0.0.1',  'server_admin': '[no address given]',  'server_name': 'www.tunisiya.org',  'server_port': '80',  'server_protocol': 'http/1.0',  'server_signature': '',  'server_software': 'apache/2.2.15 (unix) mod_wsgi/3.2 python/2.6.8',  'mod_wsgi.application_group': 'tunisiya2.com|',  'mod_wsgi.callable_object': 'application',  'mod_wsgi.handler_script': '',  'mod_wsgi.input_chunked': '0',  'mod_wsgi.listener_host': '',  'mod_wsgi.listener_port': '39877',  'mod_wsgi.process_group': '',  'mod_wsgi.request_handler': 'wsgi-script',  'mod_wsgi.script_reloading': '1',  'mod_wsgi.version': (3, 2),  'wsgi.errors': <mod_wsgi.log object @ 0xd69b570>,  'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.adapter object @ 0xa7efda0>,  'wsgi.input': <mod_wsgi.input object @ 0xd69b598>,    'wsgi.multiprocess': false,  'wsgi.multithread': true,  'wsgi.run_once': false,  'wsgi.url_scheme': 'http',  'wsgi.version': (1, 1)}> 

wrap make_concordance in try-except; if exception occurs, render original form template user, along error information.

import re try:     context, texts_len, results_len = make_concordance(searchterm, search_type) except re.error e:     form._errors['search_term'] = str(e)     del form.cleaned_data['search_term']      return render_to_response('corpus/search_test.html',           {'form': form}, context_instance=requestcontext(request)) 

the better way make custom cleaner, seems bit more complicated, , not have django.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -