def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optioal, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) """ # create a fake request object request = HttpRequest() # Loookup the request path: if namespace: view_name = namespace + ":" + view_name request.path = reverse(view_name, args=args) # get cache key, expire if the cached item exists: key = get_cache_key(request, key_prefix=key_prefix) log_to_file('deleting view cache: %s, view: %s' % (key, view_name)) if key: #if cache.get(key): # cache.set(key, None, 0) #return True if cache.has_key(key): cache.delete(key) log_to_file('cache deleted %s, view: %s' % (key, view_name)) return True return False
def get_dependencies(request, lib_id): " get dependencies for current library version " try: lib_id = int(lib_id) except: log_to_file("ERROR: get_dependencies called with lib_id: %s" % lib_id) raise Http404 return HttpResponse(simplejson.dumps(get_dependencies_dict(lib_id)), mimetype='application/json')
def pastie_edit(req, slug=None, version=None, revision=None, author=None, skin=None): """ display the edit shell page ( main display) """ # build the cache key on the basis of url and user try: key = get_pastie_edit_key(req, slug, version, revision, author, skin) except Exception, err: log_to_file("ERROR: pastie_edit: " "generating key failed, vars: %s %s" % ( str([slug, version, revision, author]), str(err))) return HttpResponseNotAllowed("Error in generating the key")
def build_dict(pastie): shell = pastie.favourite if not shell.author: log_to_file("WARNING: Shell has no author %s" % shell.get_absolute_url()) return { "title": shell.title, "author": shell.author.username if shell.author else "no author", "description": shell.description, "url": "%s%s" % (server, shell.get_absolute_url()), "version": shell.version, "created": shell.created_at.strftime("%Y-%m-%d %H:%I:%S"), "framework": shell.js_lib.library_group.name, "latest_version": pastie.get_latest().version, }
def add_external_resource(req): url = req.POST.get("url") try: # check if url already in models resource = ExternalResource.objects.get(url=url) log_to_file("resource %s chosen" % resource.filename) except: # else create resource resource = ExternalResource(url=url) resource.save() log_to_file("resource %s created" % resource.filename) return HttpResponse( simplejson.dumps( {"id": resource.id, "url": resource.url, "filename": resource.filename, "extension": resource.extension} ), mimetype="application/javascript", )
def make_favourite(req): " set the base version " shell_id = req.POST.get('shell_id', None) if not shell_id: log_to_file('ERROR: make_favourite: no shell_id') return HttpResponse( simplejson.dumps({ 'error': "<p>No shell id - if you think it is an error." "please <a href='*****@*****.**'>email us</a>.</p>" "<p>The error has been logged</p>"})) try: shell = Shell.objects.get(id=shell_id) except ObjectDoesNotExist, err: log_to_file("ERROR: make_favourite: Shell doesn't exist " "%s" % str(shell_id)) raise Http404
def pastie_show(req, slug, version=None, author=None, skin=None): " render the shell only " key = get_pastie_show_key(slug, version, author, 'shell') if cache.has_key(key): shell = cache.get(key) else: pastie = get_object_or_404(Pastie, slug=slug) if version == None: shell = pastie.favourite else: user = get_object_or_404(User,username=author) if author else None try: shell = get_object_or_404(Shell, pastie__slug=slug, version=version, author=user) except MultipleObjectsReturned: log_to_file('WARNING: pastie_show: ' 'Multiple shells in pastie_show: %s, %s' % (slug, version)) shell = list(Shell.objects.filter(pastie__slug=slug, version=version, author=user))[0] cache.set(key, shell) if not skin: skin = req.GET.get('skin', settings.MOOSHELL_DEFAULT_SKIN) key = get_pastie_show_key(slug, version, author, 'resources') if cache.has_key(key): resources = cache.get(key) else: resources = [res.resource for res in \ ShellExternalResource.objects.filter(shell__id=shell.id)] cache.set(key, resources) key = get_pastie_show_key(slug, version, author, 'dependencies') if cache.has_key(key): dependencies = cache.get(key) else: dependencies = shell.js_dependency.all() cache.set(key, dependencies) return pastie_display(req, slug, shell, dependencies=dependencies, resources=resources, skin=skin)
def get_library_versions(request, group_id): " get library versions for current framework " try: group_id = int(group_id) except: log_to_file("ERROR: get_library_versions called with group_id:" " %s" % group_id) raise Http404 libraries = JSLibrary.objects.filter(library_group__id=group_id) c = {'libraries': [ { 'id': l.id, 'version': l.version, 'selected': l.selected, 'group_name': l.library_group.name, 'active': l.active } for l in libraries ] } selected = [l for l in libraries if l.selected] if selected: selected = selected[0] c['dependencies'] = get_dependencies_dict(selected.id) return HttpResponse(simplejson.dumps(c),mimetype='application/json')
def expire_page(path): request = HttpRequest() request.path = path key = get_cache_key(request) log_to_file('deleting cache: %s, path: %s' % (key, request.path)) if cache.has_key(key): cache.delete(key) log_to_file('cache deleted %s, path: %s' % (key, request.path)) else: log_to_file('no such key %s' % key)
def api_get_users_pasties(req, author, method='json'): " JS API returns user's fiddles " # receiving query parameters start = int(req.GET.get('start',0)) limit = start + int(req.GET.get('limit',10)) framework = req.GET.get('framework', '') sort = None if SORT_CHOICES.has_key(req.GET.get('sort', False)): sort= SORT_CHOICES[req.GET['sort']] if ORDER_CHOICES.has_key(req.GET.get('order', False)): order = ORDER_CHOICES[req.GET['order']] else: order = '' order_by = '%s%s' % (order, sort) else: order_by = False # jsoncallback is historical callback = req.GET.get('jsoncallback', None) # callback is a industry standard if not callback: callback = req.GET.get('callback', None) user = get_object_or_404(User, username=author) pasties_filter = Pastie.objects\ .filter(author__username=author) if framework != '': pasties_filter = pasties_filter\ .filter(favourite__js_lib__library_group__name=framework) pasties_objects = pasties_filter\ .exclude(favourite__title__isnull=True)\ .exclude(favourite__title="")\ .order_by('-created_at') if order_by: pasties_ordered = pasties_objects\ .order_by(order_by) else: pasties_ordered = pasties_objects overall_result_set_count = len(pasties_objects) pasties = pasties_ordered[start:limit] try: server = settings.MOOSHELL_FORCE_SERVER except: server = 'http://%s' % req.META['SERVER_NAME'] try: return render_to_response('api/pasties.%s' % method, { 'pasties': pasties, 'server': server, 'callback': callback, 'overallResultSetCount': overall_result_set_count }, context_instance=RequestContext(req), mimetype="application/javascript") except TemplateDoesNotExist: log_to_file('WARNING: api_get_users_pasties: no such type: ' '%s' % method) raise Http404()
def embedded(req, slug, version=None, revision=0, author=None, tabs=None, skin=None): " display embeddable version of the shell " allowed_tabs = ('js', 'html', 'css', 'result', 'resources') key = get_embedded_key(req, slug, version, revision, author, tabs, skin) context = None try: context = cache.get(key, None) except Exception: log_to_file('ERROR: embedded: Getting cache key failed: %s' % key) return HttpResponseNotAllowed('Error in cache') if not context: pastie = get_object_or_404(Pastie,slug=slug) if version == None: shell = pastie.favourite else: user = get_object_or_404(User,username=author) if author else None try: shell = Shell.objects.get(pastie__slug=slug, version=version, author=user) except MultipleObjectsReturned: # MySQL created some duplicate Shells shell = Shell.objects.filter(pastie__slug=slug, version=version, author=user)[0] except ObjectDoesNotExist: raise Http404 if not skin: skin = req.GET.get('skin', settings.MOOSHELL_DEFAULT_SKIN) if not tabs: tabs = req.GET.get('tabs', 'js,resources,html,css,result') server = settings.MOOSHELL_FORCE_SERVER \ if hasattr(settings, 'MOOSHELL_FORCE_SERVER') \ else 'http://%s' % req.META['SERVER_NAME'] height = req.GET.get('height', None) tabs_order = tabs #req.GET.get('tabs',"js,html,css,result") tabs_order = tabs_order.split(',') if not shell.external_resources.all() and "resources" in tabs_order: tabs_order.remove("resources") external_resources = [] else: resources = ShellExternalResource.objects.filter( shell__id=shell.id) external_resources = [res.resource for res in resources] if [x for x in tabs_order if x not in allowed_tabs]: return HttpResponseNotAllowed('Tab name not allowed') tabs = [] titles = settings.MOOSHELL_EMBEDDED_TITLES if shell.panel_html: titles['html'] = shell.PANEL_HTML[shell.panel_html] else: titles['html'] = shell.PANEL_HTML[0] if shell.panel_css: titles['css'] = shell.PANEL_CSS[shell.panel_css] else: titles['css'] = shell.PANEL_CSS[0] if shell.panel_js: titles['js'] = shell.PANEL_JS[shell.panel_js] else: titles['js'] = shell.PANEL_JS[0] for t in tabs_order: tab = { 'type': t, 'title': titles[t] } if not t in ["result", "resources"]: tab['code'] = getattr(shell, 'code_' + t) tabs.append(tab) context = { 'height': height, 'server': server, 'shell': shell, 'external_resources': external_resources, 'skin': skin, 'tabs': tabs, 'code_tabs': ['js', 'css', 'html'], 'css_files': [ reverse('mooshell_css', args=["embedded-%s.css" % skin]) ], 'js_libs': [ reverse('mooshell_js', args=[settings.MOOTOOLS_CORE]), reverse('mooshell_js', args=[settings.MOOTOOLS_MORE]), ] } cache.set(key, context) page = render_to_response('embedded.html', context, context_instance=RequestContext(req)) return page
def pastie_save(req, nosave=False, skin=None): """ retrieve shell from the form, save or display Fix dependency """ if req.method == 'POST': slug = req.POST.get('slug', None) if slug: " UPDATE - get the instance if slug provided " pastie = get_object_or_404(Pastie,slug=slug) #pastieform = PastieForm(req.POST, instance=pastieinstance) else: " CREATE " pastie = Pastie() if not nosave: if req.user.is_authenticated(): pastie.author = req.user pastie.save() draftonly=req.POST.get('draftonly', False) shellform = ShellForm(req.POST) if shellform.is_valid(): " Instantiate shell data from the form " shell = shellform.save(commit=False) if not shell.panel_html: # XXX: A hack to pass the form shell.panel_html = 0 " Base64 decode " try: shell.code_js = base64.b64decode(shell.code_js) except: pass try: shell.code_html = base64.b64decode(shell.code_html) except: pass try: shell.code_css = base64.b64decode(shell.code_css) except: pass " Connect shell with pastie " shell.pastie = pastie # get javascript dependencies dependency_ids = [int(dep[1]) for dep in req.POST.items() \ if dep[0].startswith('js_dependency')] dependencies = [] for dep_id in dependency_ids: dep = JSDependency.objects.get(id=dep_id) dependencies.append(dep) dependencies = sorted( dependencies, key=lambda d: d.ord, reverse=True) # append external resources external_resources = [] ext_ids = req.POST.get('add_external_resources', '').split(',') for ext_id in ext_ids: if ext_id: try: external_resources.append( ExternalResource.objects.get(id=int(ext_id))) except Exception, err: log_to_file('WARNING: pastie_save: ' 'No external resource: %s %s' % ( req.POST.get('slug', '-'), ext_id)) if nosave: # get page # no need to connect with pastie display_page = pastie_display(req, None, shell, dependencies=dependencies, resources=external_resources, skin=skin) # save the draft version if req.POST.get('username', False): Draft.objects.make(req.POST.get('username'), display_page) if draftonly: hashtag = ''.join( [choice('abcdefghjkmnpqrstuvwxyz') for i in range(3)]) mdraft_url = "%s%s" % (settings.MOOSHELL_FORCE_SERVER, reverse('mdraft', args=[hashtag])) return HttpResponse(""" <p>EXPERIMENTAL</p> <p>Please load result <a target="_draft" href="%s">%s</a> on mobile and <a href="http://debug.phonegap.com/client/#jsf_%s"> debugger</a> on the desktop (Chrome, Safari, weinre app)</p> <p><a target="_blank" href="http://pmuellr.github.com/weinre/">weinre</a> service provided by <a target="_blank" href="http://phonegap.com/">PhoneGap</p>""" % ( mdraft_url, mdraft_url, hashtag)) return display_page # add user to shell if anyone logged in if req.user.is_authenticated(): shell.author = req.user try: shell.save() except Exception, err: log_to_file("ERROR: pastie_edit: " "saving shell failed %s" % str(err)) return HttpResponseNotAllowed('Error saving shell') # add saved dependencies for dep in dependencies: shell.js_dependency.add(dep) # add saved external resources for idx,ext in enumerate(external_resources): ShellExternalResource.objects.create( shell=shell, resource=ext, ord=idx) " return json with pastie url " return HttpResponse(simplejson.dumps({ 'pastie_url_relative': shell.get_absolute_url() }),mimetype='application/json' )
# shell is the base version of the fiddle shell = pastie.favourite # validate the author exists if provided if not user: user = get_object_or_404(User, username=author) if author else None else: if not user: user = get_object_or_404(User, username=author) if author else None # if shell has an author, username has to be provided in url try: shell = get_object_or_404(Shell, pastie__slug=slug, version=version, author=user) except MultipleObjectsReturned: log_to_file('WARNING: pastie_edit: ' "Multiple shells: %s, %s" % (slug, version)) shell = list(Shell.objects.filter(pastie__slug=slug, version=version, author=user))[0] except: raise external_resources = ShellExternalResource.objects.filter( shell__id=shell.id) example_url = ''.join([server, shell.get_absolute_url()]) embedded_url = ''.join([server, shell.get_embedded_url()]) disqus_url = ''.join([server, shell.pastie.favourite.get_absolute_url()]) c['embedded_url'] = embedded_url title = shell.title \ if shell.title else settings.MOOSHELL_VIEW_TITLE