1 from django.http import HttpResponse
2 from django.template import RequestContext, Template, Context
3 from django.shortcuts import render_to_response
4 from django.core.exceptions import ObjectDoesNotExist
6 from samplebc.bcmagic import models
11 from samplebc.bcmagic import forms
15 Display a barcode magic input box
17 form = forms.BarcodeMagicForm()
19 return render_to_response('bcmagic.html', {'bcmagic': form},
20 context_instance=RequestContext(request))
23 def __magic_process(text):
25 Based on scanned text, check to see if there is map object to use
26 for a useful redirect.
29 split_text = text.split('|')
31 # There should always be at least one | in a valid scan.
32 if len(split_text) <= 1:
33 return {'mode': 'Error',
34 'status': 'Invalid text: %s' % (text)}
36 # Keyword is the first element in the list
37 keyword = split_text[0]
39 # Attempt to find a KeywordMap based on keyword
41 keymap = models.KeywordMap.objects.get(keyword=keyword)
42 except ObjectDoesNotExist, e:
43 return {'mode': 'Error',
44 'status': 'Keyword (%s) is not defined' % (keyword)}
46 # Remove keyword and only scan the content
47 content = '|'.join(split_text[1:])
49 #FIXME: would be faster to cache compiled regex
50 search = re.compile(keymap.regex)
52 mo = search.search(content)
54 # if the search was invalid
56 return {'mode': 'Error',
57 'status': '(%s) failed to match (%s)' % (keymap.regex, content)}
59 t = Template(keymap.url_template)
60 c = Context(mo.groupdict())
62 return {'mode': 'redirect',
63 'url': str(t.render(c)) }
75 if 'text' in request.POST:
76 text = request.POST['text']
80 #return HttpResponse(json.write(request.POST.items()), 'text/plain')
81 if text is None or text.strip() == '':
83 d['status'] = 'Did not recieve text'
84 return HttpResponse(json.write(d), 'text/plain')
86 if text.split('|')[0] == 'url':
87 d['mode'] = 'redirect'
88 d['url'] = text.split('|')[1]
90 d = __magic_process(text)
92 return HttpResponse(json.write(d), 'text/plain')
96 def json_test(request):
99 if 'text' in request.POST:
100 text = request.POST['text']
104 #return HttpResponse(json.write(request.POST.items()), 'text/plain')
105 if text is None or text.strip() == '':
107 d['status'] = 'Did not recieve text'
108 return HttpResponse(json.write(d), 'text/plain')
110 if text.split('|')[0] == 'url':
111 d['mode'] = 'redirect'
112 d['url'] = text.split('|')[1]
114 d['msg'] = 'Recieved text: %s' % (text)
117 return HttpResponse(json.write(d), 'text/plain')