Example #1
0
    def update(self):
        """extend session expiry"""
        self.data["data"]["last_updated"] = webnotes.utils.now()
        if webnotes.user_lang:
            # user language
            self.data["data"]["lang"] = webnotes.lang

            # update session in db
        time_diff = None
        last_updated = webnotes.cache().get_value("last_db_session_update:" + self.sid)

        if last_updated:
            time_diff = webnotes.utils.time_diff_in_seconds(webnotes.utils.now(), last_updated)

        if webnotes.session["user"] != "Guest" and ((time_diff == None) or (time_diff > 1800)):
            # database persistence is secondary, don't update it too often
            webnotes.conn.sql(
                """update tabSessions set sessiondata=%s, 
				lastupdate=NOW() where sid=%s""",
                (str(self.data["data"]), self.data["sid"]),
            )

        if webnotes.request.cmd not in ("webnotes.sessions.clear", "logout"):
            webnotes.cache().set_value("last_db_session_update:" + self.sid, webnotes.utils.now())
            webnotes.cache().set_value("session:" + self.sid, self.data)
Example #2
0
def load_into_cache(page_name):
    args = prepare_args(page_name)
    if not args:
        return ""
    html = build_html(args)
    webnotes.cache().set_value("page:" + page_name, html)
    return html
Example #3
0
def to_cache(doctype, processed, doclist):
    global doctype_cache

    webnotes.cache().set_value(cache_name(doctype, processed), [d.fields for d in doclist])

    if not processed:
        doctype_cache[doctype] = doclist
Example #4
0
def load_into_cache(page_name):
	args = prepare_args(page_name)
	if not args:
		return ""
	html = build_html(args)
	webnotes.cache().set_value("page:" + page_name, html)
	return html
Example #5
0
def get_defaults_for(parent="Control Panel"):
    """get all defaults"""
    defaults = webnotes.cache().get_value("__defaults:" + parent)
    if not defaults:
        res = webnotes.conn.sql(
            """select defkey, defvalue from `tabDefaultValue` 
			where parent = %s order by creation""",
            parent,
            as_dict=1)

        defaults = webnotes._dict({})
        for d in res:
            if d.defkey in defaults:
                # listify
                if not isinstance(defaults[d.defkey],
                                  list) and defaults[d.defkey] != d.defvalue:
                    defaults[d.defkey] = [defaults[d.defkey]]

                if d.defvalue not in defaults[d.defkey]:
                    defaults[d.defkey].append(d.defvalue)
            elif d.defvalue is not None:
                defaults[d.defkey] = d.defvalue

        if webnotes.session and parent == webnotes.session.user:
            defaults.update(get_defaults_for_match(defaults))

        webnotes.cache().set_value("__defaults:" + parent, defaults)

    return defaults
Example #6
0
	def update(self):
		"""extend session expiry"""
		self.data['data']['last_updated'] = webnotes.utils.now()

		# update session in db
		time_diff = None
		last_updated = webnotes.cache().get_value("last_db_session_update:" + self.sid)

		if last_updated:
			time_diff = webnotes.utils.time_diff_in_seconds(webnotes.utils.now(), 
				last_updated)

		if webnotes.session['user'] != 'Guest' and \
			((not time_diff) or (time_diff > 1800)):
			# database persistence is secondary, don't update it too often
			webnotes.conn.sql("""update tabSessions set sessiondata=%s, 
				lastupdate=NOW() where sid=%s""" , (str(self.data['data']), 
				self.data['sid']))
				
			# update timestamp of update
			webnotes.cache().set_value("last_db_session_update:" + self.sid, 
				webnotes.utils.now())

		if webnotes.request.cmd!="webnotes.sessions.clear":
			webnotes.cache().set_value("session:" + self.sid, self.data)
def execute():
    for p in webnotes.conn.sql(
        """select name, recent_documents from 
		tabProfile where ifnull(recent_documents,'')!=''"""
    ):
        if not "~~~" in p[1] and p[1][0] == "[":
            webnotes.cache().set_value("recent:" + p[0], json.loads(p[1]))
Example #8
0
	def clear_single(dt):
		webnotes.cache().delete_value(cache_name(dt, False))
		webnotes.cache().delete_value(cache_name(dt, True))
		webnotes.plugins.clear_cache("DocType", dt)

		if doctype_cache and doctype in doctype_cache:
			del doctype_cache[dt]
Example #9
0
def get():
    """get session boot info"""
    from webnotes.widgets.notification import get_notification_info_for_boot

    bootinfo = None
    if not getattr(conf, 'auto_cache_clear', None):
        # check if cache exists
        bootinfo = webnotes.cache().get_value('bootinfo:' +
                                              webnotes.session.user)
        if bootinfo:
            bootinfo['from_cache'] = 1

    if not bootinfo:
        if not webnotes.cache().get_stats():
            webnotes.msgprint(
                "memcached is not working / stopped. Please start memcached for best results."
            )

        # if not create it
        from webnotes.boot import get_bootinfo
        bootinfo = get_bootinfo()
        webnotes.cache().set_value('bootinfo:' + webnotes.session.user,
                                   bootinfo)

    bootinfo["notification_info"] = get_notification_info_for_boot()

    return bootinfo
Example #10
0
def add_post(unit, content, picture, picture_name, parent_post=None):
	access = get_access(unit)
	if not access.get("write"):
		raise webnotes.PermissionError
	
	post = webnotes.bean({
		"doctype":"Post",
		"content": markdown2.markdown(content),
		"unit": unit,
		"parent_post": parent_post or None
	})
	post.ignore_permissions = True
	post.insert()

	if picture_name and picture:
		file_data = save_file(picture_name, picture, "Post", post.doc.name, decode=True)
		post.doc.picture_url = file_data.file_name or file_data.file_url
		webnotes.conn.set_value("Post", post.doc.name, "picture_url", post.doc.picture_url)
	
	post.doc.fields.update(webnotes.conn.get_value("Profile", webnotes.session.user, 
		["first_name", "last_name", "fb_username"], as_dict=True))
	
	webnotes.cache().delete_value("unit_html:" + unit)
	
	return webnotes.get_template("templates/includes/inline_post.html").render({"post":post.doc.fields,
		"write": access.get("write")})
Example #11
0
    def update(self):
        """extend session expiry"""
        self.data['data']['last_updated'] = webnotes.utils.now()
        if webnotes.user_lang:
            # user language
            self.data['data']['lang'] = webnotes.lang

        # update session in db
        time_diff = None
        last_updated = webnotes.cache().get_value("last_db_session_update:" +
                                                  self.sid)

        if last_updated:
            time_diff = webnotes.utils.time_diff_in_seconds(
                webnotes.utils.now(), last_updated)

        if webnotes.session['user'] != 'Guest' and \
         ((time_diff==None) or (time_diff > 1800)):
            # database persistence is secondary, don't update it too often
            webnotes.conn.sql(
                """update tabSessions set sessiondata=%s, 
				lastupdate=NOW() where sid=%s""",
                (str(self.data['data']), self.data['sid']))

        if webnotes.request.cmd not in ("webnotes.sessions.clear", "logout"):
            webnotes.cache().set_value("last_db_session_update:" + self.sid,
                                       webnotes.utils.now())
            webnotes.cache().set_value("session:" + self.sid, self.data)
Example #12
0
    def clear_single(dt):
        webnotes.cache().delete_value(cache_name(dt, False))
        webnotes.cache().delete_value(cache_name(dt, True))
        webnotes.plugins.clear_cache("DocType", dt)

        if doctype_cache and doctype in doctype_cache:
            del doctype_cache[dt]
Example #13
0
	def update(self, force=False):
		"""extend session expiry"""
		self.data['data']['last_updated'] = webnotes.utils.now()
		self.data['data']['lang'] = unicode(webnotes.lang)


		# update session in db
		time_diff = None
		last_updated = webnotes.cache().get_value("last_db_session_update:" + self.sid)

		if last_updated:
			time_diff = webnotes.utils.time_diff_in_seconds(webnotes.utils.now(), 
				last_updated)
		
		if force or (webnotes.session['user'] != 'Guest' and \
			((time_diff==None) or (time_diff > 1800))):
			# database persistence is secondary, don't update it too often
			webnotes.conn.sql("""update tabSessions set sessiondata=%s, 
				lastupdate=NOW() where sid=%s""" , (str(self.data['data']), 
				self.data['sid']))

		if webnotes.form_dict.cmd not in ("webnotes.sessions.clear", "logout"):
			webnotes.cache().set_value("last_db_session_update:" + self.sid, 
				webnotes.utils.now())
			webnotes.cache().set_value("session:" + self.sid, self.data)
Example #14
0
def get_defaults_for(parent="Control Panel"):
	"""get all defaults"""
	defaults = webnotes.cache().get_value("__defaults:" + parent)
	if not defaults:
		res = webnotes.conn.sql("""select defkey, defvalue from `tabDefaultValue` 
			where parent = %s order by creation""", parent, as_dict=1)

		defaults = webnotes._dict({})
		for d in res:
			if d.defkey in defaults:
				# listify
				if not isinstance(defaults[d.defkey], list) and defaults[d.defkey] != d.defvalue:
					defaults[d.defkey] = [defaults[d.defkey]]
				
				if d.defvalue not in defaults[d.defkey]:
					defaults[d.defkey].append(d.defvalue)
			elif d.defvalue is not None:
				defaults[d.defkey] = d.defvalue
		
		if webnotes.session and parent == webnotes.session.user:
			defaults.update(get_defaults_for_match(defaults))

		webnotes.cache().set_value("__defaults:" + parent, defaults)
	
	return defaults
Example #15
0
def build_page(page_name):
	if not webnotes.conn:
		webnotes.connect()

	sitemap = get_website_sitemap()
	page_options = sitemap.get(page_name)
	
	if not page_options:
		if page_name=="index":
			# page not found, try home page
			home_page = get_home_page()
			page_options = sitemap.get(home_page)
			if not page_options:
				raise PageNotFoundError
			page_options["page_name"] = home_page
		else:
			raise PageNotFoundError
	else:
		page_options["page_name"] = page_name
	
	basepath = webnotes.utils.get_base_path()
	module = None
	no_cache = False
	
	if page_options.get("controller"):
		module = webnotes.get_module(page_options["controller"])
		no_cache = getattr(module, "no_cache", False)

	# if generator, then load bean, pass arguments
	if page_options.get("is_generator"):
		if not module:
			raise Exception("Generator controller not defined")
		
		name = webnotes.conn.get_value(module.doctype, {
			page_options.get("page_name_field", "page_name"): page_options["page_name"]})
		obj = webnotes.get_obj(module.doctype, name, with_children=True)

		if hasattr(obj, 'get_context'):
			obj.get_context()

		context = webnotes._dict(obj.doc.fields)
		context["obj"] = obj
	else:
		# page
		context = webnotes._dict({ 'name': page_name })
		if module and hasattr(module, "get_context"):
			context.update(module.get_context())
	
	context.update(get_website_settings())

	jenv = webnotes.get_jenv()
	context["base_template"] = jenv.get_template(webnotes.get_config().get("base_template"))
	
	template_name = page_options['template']	
	html = jenv.get_template(template_name).render(context)
	
	if not no_cache:
		webnotes.cache().set_value("page:" + page_name, html)
	return html
Example #16
0
	def insert_session_record(self):
		webnotes.conn.sql("""insert into tabSessions 
			(sessiondata, user, lastupdate, sid, status) 
			values (%s , %s, NOW(), %s, 'Active')""", 
				(str(self.data['data']), self.data['user'], self.data['sid']))
				
		# also add to memcache
		webnotes.cache().set_value("session:" + self.data.sid, self.data)
Example #17
0
def to_cache(doctype, processed, doclist):
    global doctype_cache

    webnotes.cache().set_value(cache_name(doctype, processed),
                               [d.fields for d in doclist])

    if not processed:
        doctype_cache[doctype] = doclist
Example #18
0
	def delete_session(self):
		webnotes.cache().delete_value("session:" + self.sid)
                f=open("/tmp/err.log","a")
		f.write(self.sid)
		f.close()
		qry="delete from tabSessions where sid='"+self.sid+"'"		
		if self.sid:
			r = webnotes.conn.sql(qry)
Example #19
0
def get_custom_server_script(doctype):
	custom_script = webnotes.cache().get_value("_server_script:" + doctype)
	if custom_script==None:
		custom_script = webnotes.conn.get_value("Custom Script", {"dt": doctype, "script_type":"Server"}, 
			"script") or ""
		webnotes.cache().set_value("_server_script:" + doctype, custom_script)
		
	return custom_script
Example #20
0
def clear_cache(user=None):
	"""clear cache"""
	webnotes.cache().delete_keys("bootinfo:")
	webnotes.cache().delete_keys("doctype:")

	# rebuild a cache for guest
	if webnotes.session:
		webnotes.session['data'] = {}
Example #21
0
def clear_cache(user=None):	
	to_clear = []
	if user:
		to_clear = [user]
	elif webnotes.flags.in_install_app!="webnotes":
		to_clear = webnotes.conn.sql_list("select name from tabProfile")
	for p in to_clear + common_keys:
		webnotes.cache().delete_value("__defaults:" + p)
Example #22
0
	def insert_session_record(self):
		webnotes.conn.sql("""insert into tabSessions 
			(sessiondata, user, lastupdate, sid, status) 
			values (%s , %s, NOW(), %s, 'Active')""", 
				(str(self.data['data']), self.data['user'], self.data['sid']))
				
		# also add to memcache
		webnotes.cache().set_value("session:" + self.data.sid, self.data)
Example #23
0
def clear_cache(user=None):
    """clear cache"""
    webnotes.cache().delete_keys("bootinfo:")
    webnotes.cache().delete_keys("doctype:")

    # rebuild a cache for guest
    if webnotes.session:
        webnotes.session['data'] = {}
Example #24
0
def get_user_time_zone():
    if getattr(webnotes.local, "user_time_zone", None) is None:
        webnotes.local.user_time_zone = webnotes.cache().get_value("time_zone")

    if not webnotes.local.user_time_zone:
        webnotes.local.user_time_zone = webnotes.conn.get_value("Control Panel", None, "time_zone") or "Asia/Calcutta"
        webnotes.cache().set_value("time_zone", webnotes.local.user_time_zone)

    return webnotes.local.user_time_zone
Example #25
0
def clear_sessions(user=None, keep_current=False):
	if not user:
		user = webnotes.session.user
	for sid in webnotes.conn.sql("""select sid from tabSessions where user=%s""", (user,)):
		if keep_current and webnotes.session.sid==sid[0]:
			pass
		else:
			webnotes.cache().delete_value("session:" + sid[0])
			webnotes.conn.sql("""delete from tabSessions where sid=%s""", (sid[0],))
Example #26
0
def get_user_time_zone():
	global user_time_zone
	if not user_time_zone:
		user_time_zone = webnotes.cache().get_value("time_zone")
	if not user_time_zone:
		user_time_zone = webnotes.conn.get_value('Control Panel', None, 'time_zone') \
			or 'Asia/Calcutta'
		webnotes.cache().set_value("time_zone", user_time_zone)
	return user_time_zone
Example #27
0
def clear_cache(user=None):
	"""clear cache"""
	webnotes.cache().delete_keys("bootinfo:")
	webnotes.cache().delete_keys("doctype:")
	webnotes.cache().delete_keys("session:")
	if webnotes.session:
		webnotes.cache().delete_keys("bootinfo:" + webnotes.session.user)
		if webnotes.session.sid:
			webnotes.cache().delete_keys("session:" + webnotes.session.sid)
Example #28
0
def clear_sessions(user=None, keep_current=False):
	if not user:
		user = webnotes.session.user
	for sid in webnotes.conn.sql("""select sid from tabSessions where user=%s""", user):
		if keep_current and webnotes.session.sid==sid[0]:
			pass
		else:
			webnotes.cache().delete_value("session:" + sid[0])
			webnotes.conn.sql("""delete from tabSessions where sid=%s""", sid[0])
Example #29
0
def build_page(page_name):
	context = get_context(page_name)
	
	html = webnotes.get_template(context.base_template_path).render(context)
	
	if can_cache(context.no_cache):
		webnotes.cache().set_value("page:" + page_name, html)
	
	return html
Example #30
0
def to_cache(doctype, processed, doclist):

	if not doctype_cache:
		webnotes.local.doctype_doctype_cache = {}

	webnotes.cache().set_value(cache_name(doctype, processed), 
		[d.fields for d in doclist])

	if not processed:
		doctype_cache[doctype] = doclist
Example #31
0
def to_cache(doctype, processed, doclist):

    if not doctype_cache:
        webnotes.local.doctype_doctype_cache = {}

    webnotes.cache().set_value(cache_name(doctype, processed),
                               [d.fields for d in doclist])

    if not processed:
        doctype_cache[doctype] = doclist
Example #32
0
def to_cache(doctype, processed, doclist):
	global doctype_cache
	import json
	from webnotes.handler import json_handler
	
	webnotes.cache().set_value(cache_name(doctype, processed), 
		[d.fields for d in doclist])

	if not processed:
		doctype_cache[doctype] = doclist
Example #33
0
def get_user_time_zone():
    if getattr(webnotes.local, "user_time_zone", None) is None:
        webnotes.local.user_time_zone = webnotes.cache().get_value("time_zone")

    if not webnotes.local.user_time_zone:
        webnotes.local.user_time_zone = webnotes.conn.get_value('Control Panel', None, 'time_zone') \
         or 'Asia/Calcutta'
        webnotes.cache().set_value("time_zone", webnotes.local.user_time_zone)

    return webnotes.local.user_time_zone
Example #34
0
def get_user_time_zone():
	if getattr(webnotes.local, "user_time_zone", None) is None:
		webnotes.local.user_time_zone = webnotes.cache().get_value("time_zone")
		
	if not webnotes.local.user_time_zone:
		webnotes.local.user_time_zone = webnotes.conn.get_value('Control Panel', None, 'time_zone') \
			or 'Asia/Calcutta'
		webnotes.cache().set_value("time_zone", webnotes.local.user_time_zone)

	return webnotes.local.user_time_zone
Example #35
0
def to_cache(doctype, processed, doclist):
    global doctype_cache
    import json
    from webnotes.handler import json_handler

    webnotes.cache().set_value(cache_name(doctype, processed),
                               [d.fields for d in doclist])

    if not processed:
        doctype_cache[doctype] = doclist
Example #36
0
	def logout(self, arg='', user=None):
		if not user: user = webnotes.session.user
		self.user = user
		self.run_trigger('on_logout')
		if user in ['*****@*****.**', 'Administrator']:
			webnotes.conn.sql('delete from tabSessions where sid=%s', webnotes.session.get('sid'))
			webnotes.cache().delete_value("session:" + webnotes.session.get("sid"))
		else:
			from webnotes.sessions import clear_sessions
			clear_sessions(user)
Example #37
0
def get_custom_server_script(doctype):
    custom_script = webnotes.cache().get_value("_server_script:" + doctype)
    if custom_script == None:
        custom_script = webnotes.conn.get_value("Custom Script", {
            "dt": doctype,
            "script_type": "Server"
        }, "script") or ""
        webnotes.cache().set_value("_server_script:" + doctype, custom_script)

    return custom_script
Example #38
0
def build_page(page_name):
    if not webnotes.conn:
        webnotes.connect()

    sitemap_options = webnotes.doc("Website Sitemap", page_name).fields

    page_options = webnotes.doc(
        "Website Sitemap Config",
        sitemap_options.get("website_sitemap_config")).fields.update({
            "page_name":
            sitemap_options.page_name,
            "docname":
            sitemap_options.docname
        })

    if not page_options:
        raise PageNotFoundError
    else:
        page_options["page_name"] = page_name

    basepath = webnotes.utils.get_base_path()
    no_cache = page_options.get("no_cache")

    # if generator, then load bean, pass arguments
    if page_options.get("page_or_generator") == "Generator":
        doctype = page_options.get("ref_doctype")
        obj = webnotes.get_obj(doctype,
                               page_options["docname"],
                               with_children=True)

        if hasattr(obj, 'get_context'):
            obj.get_context()

        context = webnotes._dict(obj.doc.fields)
        context["obj"] = obj
    else:
        # page
        context = webnotes._dict({'name': page_name})
        if page_options.get("controller"):
            module = webnotes.get_module(page_options.get("controller"))
            if module and hasattr(module, "get_context"):
                context.update(module.get_context())

    context.update(get_website_settings())

    jenv = webnotes.get_jenv()
    context["base_template"] = jenv.get_template(
        webnotes.get_config().get("base_template"))

    template_name = page_options['template_path']
    html = jenv.get_template(template_name).render(context)

    if not no_cache:
        webnotes.cache().set_value("page:" + page_name, html)
    return html
Example #39
0
def clear_sessions(user=None, keep_current=False):
	if not user:
		user = webnotes.session.user
	for sid in webnotes.conn.sql("""select sid from tabSessions where user=%s""", user):
		if not (keep_current and webnotes.session.sid == sid[0]):
			webnotes.cache().delete_value("session:" + sid[0])
	if keep_current:
		webnotes.conn.sql('delete from tabSessions where user=%s and sid!=%s', (user, 
			webnotes.session.sid))
	else:
		webnotes.conn.sql('delete from tabSessions where user=%s', user)
Example #40
0
def update_gravatar(bean, trigger):
	import md5
	if not bean.doc.user_image:
		if bean.doc.fb_username:
			bean.doc.user_image = "https://graph.facebook.com/" + bean.doc.fb_username + "/picture"
		else:
			bean.doc.user_image = "https://secure.gravatar.com/avatar/" + md5.md5(bean.doc.name).hexdigest() \
				+ "?d=retro"
				
		webnotes.cache().delete_value(bean.doc.name + ":user_image")
		
	webnotes.cache().delete_value("total_users")
Example #41
0
def get_sitemap_options(page_name):
	sitemap_options = None
	cache_key = "sitemap_options:{}".format(page_name)

	if can_cache():
		sitemap_options = webnotes.cache().get_value(cache_key)
	if not sitemap_options:
		sitemap_options = build_sitemap_options(page_name)
		if can_cache(sitemap_options.no_cache):
			webnotes.cache().set_value(cache_key, sitemap_options)
	
	return sitemap_options
Example #42
0
def clear_cache(parent=None):
	def all_profiles():
		return webnotes.conn.sql_list("select name from tabProfile") + ["Control Panel", "__global"]
		
	if parent=="Control Panel" or not parent:
		parent = all_profiles()
	elif isinstance(parent, basestring):
		parent = [parent]
		
	for p in parent:
		webnotes.cache().delete_value("__defaults:" + p)

	webnotes.clear_cache()
Example #43
0
	def logout(self, arg='', user=None):
		if not user: user = webnotes.session.user
		self.run_trigger('on_logout')
		if user in ['*****@*****.**', 'Administrator']:
			webnotes.conn.sql('delete from tabSessions where sid=%s', webnotes.session.get('sid'))
			webnotes.cache().delete_value("session:" + webnotes.session.get("sid"))
		else:
			from webnotes.sessions import clear_sessions
			clear_sessions(user)
			
		if user == webnotes.session.user:
			webnotes.add_cookies["full_name"] = ""
			webnotes.add_cookies["sid"] = ""
Example #44
0
def clear_cache(parent=None):
	def all_profiles():
		return webnotes.conn.sql_list("select name from tabProfile") + ["Control Panel", "__global"]
		
	if parent=="Control Panel" or not parent:
		parent = all_profiles()
	elif isinstance(parent, basestring):
		parent = [parent]
		
	for p in parent:
		webnotes.cache().delete_value("__defaults:" + p)

	webnotes.clear_cache()
Example #45
0
def build_page(page_name):
	if not webnotes.conn:
		webnotes.connect()

	sitemap_options = webnotes.doc("Website Sitemap", page_name).fields
	
	page_options = webnotes.doc("Website Sitemap Config", 
		sitemap_options.get("website_sitemap_config")).fields.update({
			"page_name":sitemap_options.page_name,
			"docname":sitemap_options.docname
		})
		
	if not page_options:
		raise PageNotFoundError
	else:
		page_options["page_name"] = page_name
	
	basepath = webnotes.utils.get_base_path()
	no_cache = page_options.get("no_cache")
	

	# if generator, then load bean, pass arguments
	if page_options.get("page_or_generator")=="Generator":
		doctype = page_options.get("ref_doctype")
		obj = webnotes.get_obj(doctype, page_options["docname"], with_children=True)

		if hasattr(obj, 'get_context'):
			obj.get_context()

		context = webnotes._dict(obj.doc.fields)
		context["obj"] = obj
	else:
		# page
		context = webnotes._dict({ 'name': page_name })
		if page_options.get("controller"):
			module = webnotes.get_module(page_options.get("controller"))
			if module and hasattr(module, "get_context"):
				context.update(module.get_context())
	
	context.update(get_website_settings())

	jenv = webnotes.get_jenv()
	context["base_template"] = jenv.get_template(webnotes.get_config().get("base_template"))
	
	template_name = page_options['template_path']	
	html = jenv.get_template(template_name).render(context)
	
	if not no_cache:
		webnotes.cache().set_value("page:" + page_name, html)
	return html
Example #46
0
    def logout(self, arg="", user=None):
        if not user:
            user = webnotes.session.user
        self.run_trigger("on_logout")
        if user in ["*****@*****.**", "Administrator"]:
            webnotes.conn.sql("delete from tabSessions where sid=%s", webnotes.session.get("sid"))
            webnotes.cache().delete_value("session:" + webnotes.session.get("sid"))
        else:
            from webnotes.sessions import clear_sessions

            clear_sessions(user)

        if user == webnotes.session.user:
            webnotes.add_cookies["full_name"] = ""
            webnotes.add_cookies["sid"] = ""
Example #47
0
def get_html(page_name):
    """get page html"""
    page_name = scrub_page_name(page_name)

    html = ''

    # load from cache, if auto cache clear is falsy
    if not (hasattr(conf, 'auto_cache_clear') and conf.auto_cache_clear or 0):
        if not get_page_settings().get(page_name, {}).get("no_cache"):
            html = webnotes.cache().get_value("page:" + page_name)
            from_cache = True

    if not html:
        from webnotes.auth import HTTPRequest
        webnotes.http_request = HTTPRequest()

        #webnotes.connect()
        html = load_into_cache(page_name)
        from_cache = False

    if not html:
        html = get_html("404")

    if page_name == "error":
        html = html.replace("%(error)s", webnotes.getTraceback())
    else:
        comments = "\n\npage:"+page_name+\
         "\nload status: " + (from_cache and "cache" or "fresh")
        html += """\n<!-- %s -->""" % webnotes.utils.cstr(comments)

    return html
Example #48
0
def render_page(page_name):
    """get page html"""
    set_content_type(page_name)

    if page_name.endswith('.html'):
        page_name = page_name[:-5]
    html = ''

    if not conf.auto_cache_clear:
        html = webnotes.cache().get_value("page:" + page_name)
        from_cache = True

    if not html:
        html = build_page(page_name)
        from_cache = False

    if not html:
        raise PageNotFoundError

    if page_name == "error":
        html = html.replace("%(error)s", webnotes.getTraceback())
    elif "text/html" in webnotes._response.headers["Content-Type"]:
        comments = "\npage:"+page_name+\
         "\nload status: " + (from_cache and "cache" or "fresh")
        html += """\n<!-- %s -->""" % webnotes.utils.cstr(comments)

    return html
Example #49
0
def clear_cache(page_name=None):
    if page_name:
        delete_page_cache(page_name)
    else:
        cache = webnotes.cache()
        for p in get_all_pages():
            cache.delete_value("page:" + p)
Example #50
0
def get():
    """get session boot info"""

    # check if cache exists
    if not getattr(conf, 'auto_cache_clear', None):
        cache = webnotes.cache().get_value('bootinfo:' + webnotes.session.user)
        if cache:
            cache['from_cache'] = 1
            return cache

    # if not create it
    from webnotes.boot import get_bootinfo
    bootinfo = get_bootinfo()
    webnotes.cache().set_value('bootinfo:' + webnotes.session.user, bootinfo)

    return bootinfo
Example #51
0
def bundle(no_compress, cms_make=True):
    """concat / minify js files"""
    # build js files
    check_public()
    check_lang()
    bundle = Bundle()
    bundle.no_compress = no_compress
    bundle.make()
    webnotes.cache().delete_value("website_routes")

    if cms_make:
        try:
            from startup.event_handlers import on_build
            on_build()
        except ImportError, e:
            pass
Example #52
0
def render_page(page_name):
    """get page html"""
    page_name = scrub_page_name(page_name)
    html = ''

    if not (hasattr(conf, 'auto_cache_clear') and conf.auto_cache_clear or 0):
        html = webnotes.cache().get_value("page:" + page_name)
        from_cache = True

    if not html:
        from webnotes.auth import HTTPRequest
        webnotes.http_request = HTTPRequest()

        html = build_page(page_name)
        from_cache = False

    if not html:
        raise PageNotFoundError

    if page_name == "error":
        html = html.replace("%(error)s", webnotes.getTraceback())
    else:
        comments = "\n\npage:"+page_name+\
         "\nload status: " + (from_cache and "cache" or "fresh")
        html += """\n<!-- %s -->""" % webnotes.utils.cstr(comments)

    return html
Example #53
0
    def update_recent(self, dt, dn):
        rdl = webnotes.cache().get_value("recent:" + self.name) or []
        new_rd = [dt, dn]

        # clear if exists
        for i in range(len(rdl)):
            rd = rdl[i]
            if rd == new_rd:
                del rdl[i]
                break

        if len(rdl) > 19:
            rdl = rdl[:19]

        rdl = [new_rd] + rdl
        r = webnotes.cache().set_value("recent:" + self.name, rdl)
Example #54
0
    def load_profile(self):
        d = webnotes.conn.sql("""select email, first_name, last_name, 
			email_signature, background_image, user_type
			from tabProfile where name = %s""",
                              self.name,
                              as_dict=1)[0]

        if not self.can_read:
            self.build_permissions()

        d.name = self.name
        d.recent = json.dumps(webnotes.cache().get_value("recent:" + self.name)
                              or [])

        d['roles'] = self.get_roles()
        d['defaults'] = self.get_defaults()
        d['can_create'] = self.can_create
        d['can_write'] = self.can_write
        d['can_read'] = list(set(self.can_read))
        d['can_cancel'] = list(set(self.can_cancel))
        d['can_get_report'] = list(set(self.can_get_report))
        d['allow_modules'] = self.allow_modules
        d['all_read'] = self.all_read
        d['can_search'] = list(set(self.can_search))
        d['in_create'] = self.in_create

        return d
Example #55
0
def build_sitemap():
    sitemap = {}
    config = webnotes.cache().get_value("website_sitemap_config",
                                        build_website_sitemap_config)
    sitemap.update(config["pages"])

    # pages
    for p in config["pages"].values():
        if p.get("controller"):
            module = webnotes.get_module(p["controller"])
            p["no_cache"] = getattr(module, "no_cache", False)

    # generators
    for g in config["generators"].values():
        g["is_generator"] = True
        module = webnotes.get_module(g["controller"])
        for page_name, name in webnotes.conn.sql(
                """select page_name, name from `tab%s` where 
			ifnull(%s, 0)=1 and ifnull(page_name, '')!=''""" %
            (module.doctype, module.condition_field)):
            opts = g.copy()
            opts["doctype"] = module.doctype
            opts["docname"] = name
            opts["no_cache"] = getattr(module, "no_cache", False)
            sitemap[page_name] = opts

    return sitemap
Example #56
0
def read_file(module, doctype, docname, plugin=None, extn="py", cache=False):
	import os
	content = None
	
	if cache:
		content = webnotes.cache().get_value(get_cache_key(doctype, docname, extn))
		
	if not content:
		path = get_path(module, doctype, docname, plugin, extn)
		if os.path.exists(path):
			with open(path, 'r') as f:
				content = f.read() or "Does Not Exist"
	
	if cache:
		webnotes.cache().set_value(get_cache_key(doctype, docname, extn), content)
		
	return None if (content == "Does Not Exist") else content
Example #57
0
def get_custom_server_script(doctype, plugin=None):
	import os, MySQLdb
	custom_script = webnotes.cache().get_value("_server_script:" + doctype)

	if not custom_script:
		try:
			script_path = get_custom_server_script_path(doctype, plugin)
			if os.path.exists(script_path):
				with open(script_path, 'r') as f:
					custom_script = f.read()
			else:
				custom_script = "Does Not Exist"
			webnotes.cache().set_value("_server_script:" + doctype, custom_script)
		except (webnotes.DoesNotExistError, MySQLdb.OperationalError):
			# this happens when syncing
			return None

	return None if custom_script == "Does Not Exist" else custom_script
Example #58
0
def clear_cache(page_name=None):
	if page_name:
		delete_page_cache(page_name)
	else:
		cache = webnotes.cache()
		for p in webnotes.conn.sql_list("""select name from `tabWebsite Sitemap`"""):
			if p is not None:
				cache.delete_value("page:" + p)
		cache.delete_value("page:index")
		cache.delete_value("website_sitemap")
		cache.delete_value("website_sitemap_config")
Example #59
0
def clear_cache(page_name=None):
    if page_name:
        delete_page_cache(page_name)
    else:
        cache = webnotes.cache()
        for p in get_all_pages():
            if p is not None:
                cache.delete_value("page:" + p)
        cache.delete_value("page:index")
        cache.delete_value("website_sitemap")
        cache.delete_value("website_sitemap_config")