- added Java session access implementations - Added examples directorymaster
@@ -0,0 +1,38 @@ | |||
import java.io.*; | |||
import javax.servlet.*; | |||
import javax.servlet.http.*; | |||
import com.cppcms.session.*; | |||
public class Sample extends HttpServlet { | |||
static SessionPool pool; | |||
public void init() throws ServletException | |||
{ | |||
ServletContext context = getServletContext(); | |||
String libPath = context.getRealPath("/WEB-INF/lib/libcppcms.so"); | |||
String configPath = context.getRealPath("/WEB-INF/cppcms-config.js"); | |||
API.init(libPath); | |||
pool = SessionPool.openFromConfig(configPath); | |||
} | |||
public void doGet(HttpServletRequest request, | |||
HttpServletResponse response) throws ServletException, IOException | |||
{ | |||
Session session = pool.getSession(); | |||
session.load(request); | |||
String x=session.get("x"); | |||
if(x==null) { | |||
x="0"; | |||
} | |||
x=Integer.toString(Integer.parseInt(x)+1); | |||
session.set("x",x); | |||
session.save(response); | |||
session.close(); | |||
PrintWriter out = response.getWriter(); | |||
out.println("X is now " + x); | |||
// Use "out" to send content to browser | |||
} | |||
} | |||
@@ -0,0 +1,33 @@ | |||
from django.http import HttpResponse | |||
from django.conf import settings | |||
import cppcms | |||
# | |||
# Load the module containing the API | |||
# | |||
cppcms.Loader.load('libcppcms.so') | |||
# | |||
# Create the session pool - note it is thread safe and should be one per projects | |||
# Provide a path to configuration file | |||
# | |||
pool=cppcms.SessionPool(settings.BASE_DIR + '/mysite/cppcms-config.js') | |||
def home(request): | |||
# Get session object | |||
s=pool.session() | |||
# Load the data from request | |||
s.load(django_request=request) | |||
# Access session key-values as dictionary | |||
v='0' | |||
if 'x' in s: | |||
v= s['x'] | |||
s['x']=str(int(v)+1) | |||
response = HttpResponse() | |||
# Save the session | |||
s.save(django_response=response) | |||
response.write('x is %s' % v); | |||
return response |
@@ -0,0 +1,143 @@ | |||
package com.cppcms.session; | |||
import com.sun.jna.Library; | |||
import com.sun.jna.Native; | |||
import com.sun.jna.Pointer; | |||
public class API { | |||
final static int ERROR_OK=0; | |||
final static int ERROR_GENERAL=1; | |||
final static int ERROR_RUNTIME=2; | |||
final static int ERROR_INVALID_ARGUMENT=4; | |||
final static int ERROR_LOGIC=5; | |||
final static int ERROR_ALLOC=6; | |||
protected interface JnaAPI extends Library { | |||
int cppcms_capi_error(Pointer obj); | |||
String cppcms_capi_error_message(Pointer obj); | |||
String cppcms_capi_error_clear(Pointer obj); | |||
Pointer cppcms_capi_session_pool_new(); | |||
void cppcms_capi_session_pool_delete(Pointer pool); | |||
int cppcms_capi_session_pool_init(Pointer pool,String config_file); | |||
int cppcms_capi_session_pool_init_from_json(Pointer pool,String json); | |||
Pointer cppcms_capi_session_new(); | |||
void cppcms_capi_session_delete(Pointer session); | |||
int cppcms_capi_session_init(Pointer session,Pointer pool); | |||
int cppcms_capi_session_clear(Pointer session); | |||
int cppcms_capi_session_is_set(Pointer session,String key); | |||
int cppcms_capi_session_erase(Pointer session,String key); | |||
int cppcms_capi_session_get_exposed(Pointer session,String key); | |||
int cppcms_capi_session_set_exposed(Pointer session,String key,int is_exposed); | |||
String cppcms_capi_session_get_first_key(Pointer session); | |||
String cppcms_capi_session_get_next_key(Pointer session); | |||
String cppcms_capi_session_get_csrf_token(Pointer session); | |||
int cppcms_capi_session_set(Pointer session,String key,String value); | |||
String cppcms_capi_session_get(Pointer session,String key); | |||
int cppcms_capi_session_set_binary_as_hex(Pointer session,String key,String value); | |||
String cppcms_capi_session_get_binary_as_hex(Pointer session,String key); | |||
int cppcms_capi_session_set_binary(Pointer session,String key,byte[] value,int length); | |||
int cppcms_capi_session_get_binary(Pointer session,String key,byte[] buf,int buffer_size); | |||
int cppcms_capi_session_get_binary_len(Pointer session,String key); | |||
int cppcms_capi_session_reset_session(Pointer session); | |||
int cppcms_capi_session_set_default_age(Pointer session); | |||
int cppcms_capi_session_set_age(Pointer session,int t); | |||
int cppcms_capi_session_get_age(Pointer session); | |||
int cppcms_capi_session_set_default_expiration(Pointer session); | |||
int cppcms_capi_session_set_expiration(Pointer session,int t); | |||
int cppcms_capi_session_get_expiration(Pointer session); | |||
int cppcms_capi_session_set_on_server(Pointer session,int is_on_server); | |||
int cppcms_capi_session_get_on_server(Pointer session); | |||
String cppcms_capi_session_get_session_cookie_name(Pointer session); | |||
int cppcms_capi_session_load(Pointer session,String session_cookie_value); | |||
int cppcms_capi_session_save(Pointer session); | |||
Pointer cppcms_capi_session_cookie_first(Pointer session); | |||
Pointer cppcms_capi_session_cookie_next(Pointer session); | |||
void cppcms_capi_cookie_delete(Pointer cookie); | |||
String cppcms_capi_cookie_header(Pointer cookie); | |||
String cppcms_capi_cookie_header_content(Pointer cookie); | |||
String cppcms_capi_cookie_name(Pointer cookie); | |||
String cppcms_capi_cookie_value(Pointer cookie); | |||
String cppcms_capi_cookie_path(Pointer cookie); | |||
String cppcms_capi_cookie_domain(Pointer cookie); | |||
int cppcms_capi_cookie_max_age_defined(Pointer cookie); | |||
int cppcms_capi_cookie_max_age(Pointer cookie); | |||
int cppcms_capi_cookie_expires_defined(Pointer cookie); | |||
long cppcms_capi_cookie_expires(Pointer cookie); | |||
int cppcms_capi_cookie_is_secure(Pointer cookie); | |||
} | |||
protected static JnaAPI api; | |||
public static void init(String path) | |||
{ | |||
api = (JnaAPI)Native.loadLibrary(path,JnaAPI.class); | |||
} | |||
public static void init() | |||
{ | |||
init("libcppcms.so"); | |||
} | |||
public static void main(String[] args) | |||
{ | |||
if(args.length != 2) { | |||
System.out.println("usage /path/to/libcppcms.so /path/to/config.js"); | |||
return; | |||
} | |||
SessionPool p = null; | |||
Session s = null; | |||
try { | |||
String state=""; | |||
init(args[0]); | |||
p = SessionPool.openFromConfig(args[1]); | |||
s = p.getSession(); | |||
s.load(state); | |||
s.set("x","1"); | |||
s.setExposed("x",true); | |||
s.save(); | |||
CppCMSCookie[] cookies=s.getCookies(); | |||
for(CppCMSCookie c: cookies) { | |||
System.out.println(c); | |||
if(c.name.equals(s.getSessionCookieName())) | |||
state = c.value; | |||
} | |||
s.close(); | |||
s=p.getSession(); | |||
s.load(state); | |||
System.out.println("Value of x=" + s.get("x")); | |||
byte[] v=new byte[1]; | |||
v[0]=65; | |||
s.setBinary("y",v); | |||
s.save(); | |||
cookies=s.getCookies(); | |||
for(CppCMSCookie c: cookies) { | |||
System.out.println(c); | |||
if(c.name.equals(s.getSessionCookieName())) | |||
state = c.value; | |||
} | |||
s.close(); | |||
s = p.getSession(); | |||
s.load(state); | |||
byte[] v2=s.getBinary("y"); | |||
System.out.println("v2.len=" + v2.length + " v[0]=" + v[0]); | |||
s.set("x","2222"); | |||
s.save(); | |||
javax.servlet.http.Cookie[] cs=s.getServletCookies(); | |||
for(javax.servlet.http.Cookie c : cs) { | |||
System.out.println("Got=" + c.getValue()); | |||
} | |||
s.close(); | |||
} | |||
finally { | |||
if(s!=null) | |||
s.close(); | |||
if(p!=null) | |||
p.close(); | |||
} | |||
} | |||
} | |||
@@ -0,0 +1,44 @@ | |||
package com.cppcms.session; | |||
import com.sun.jna.Pointer; | |||
public class CppCMSCookie { | |||
public final String name; | |||
public final String value; | |||
public final String path; | |||
public final String domain; | |||
public final String header; | |||
public final String headerContent; | |||
public final boolean maxAgeDefined; | |||
public final int maxAge; | |||
public final boolean expiresDefined; | |||
public final long expires; | |||
public final boolean isSecure; | |||
public String toString() | |||
{ | |||
return header; | |||
} | |||
protected CppCMSCookie(Pointer p) | |||
{ | |||
try { | |||
this.name = API.api.cppcms_capi_cookie_name(p); | |||
this.value = API.api.cppcms_capi_cookie_value(p); | |||
this.path = API.api.cppcms_capi_cookie_path(p); | |||
this.domain = API.api.cppcms_capi_cookie_domain(p); | |||
this.header = API.api.cppcms_capi_cookie_header(p); | |||
this.headerContent = API.api.cppcms_capi_cookie_header_content(p); | |||
this.maxAgeDefined = API.api.cppcms_capi_cookie_max_age_defined(p)!=0; | |||
this.expiresDefined = API.api.cppcms_capi_cookie_expires_defined(p)!=0; | |||
this.maxAge = maxAgeDefined ? API.api.cppcms_capi_cookie_max_age(p) : -1; | |||
this.expires = expiresDefined ? API.api.cppcms_capi_cookie_expires(p) : -1; | |||
this.isSecure = API.api.cppcms_capi_cookie_is_secure(p)!=0; | |||
} | |||
finally { | |||
API.api.cppcms_capi_cookie_delete(p); | |||
} | |||
} | |||
} |
@@ -0,0 +1,238 @@ | |||
package com.cppcms.session; | |||
import com.sun.jna.Pointer; | |||
import java.util.ArrayList; | |||
import javax.servlet.http.Cookie; | |||
import javax.servlet.http.HttpServletRequest; | |||
import javax.servlet.http.HttpServletResponse; | |||
public class Session extends SessionBase{ | |||
public final static int EXPIRATION_FIXED=0; | |||
public final static int EXPIRATION_RENEW=1; | |||
public final static int EXPIRATION_BROWSER=2; | |||
protected Session(Pointer poolPtr) { | |||
try { | |||
d=API.api.cppcms_capi_session_new(); | |||
API.api.cppcms_capi_session_init(d,poolPtr); | |||
check(); | |||
} | |||
catch(RuntimeException e) { | |||
close(); | |||
throw e; | |||
} | |||
} | |||
void doClose() | |||
{ | |||
API.api.cppcms_capi_session_delete(d); | |||
} | |||
public void clear() { | |||
API.api.cppcms_capi_session_clear(d); | |||
check(); | |||
} | |||
public boolean isSet(String key) | |||
{ | |||
boolean r = API.api.cppcms_capi_session_is_set(d,key) != 0; | |||
check(); | |||
return r; | |||
} | |||
public void erase(String key) | |||
{ | |||
API.api.cppcms_capi_session_erase(d,key); | |||
check(); | |||
} | |||
public boolean getExposed(String key) | |||
{ | |||
boolean r=API.api.cppcms_capi_session_get_exposed(d,key)!=0; | |||
check(); | |||
return r; | |||
} | |||
public void setExposed(String key,boolean exposed) | |||
{ | |||
API.api.cppcms_capi_session_set_exposed(d,key,exposed?1:0); | |||
check(); | |||
} | |||
public String[] getKeys() | |||
{ | |||
ArrayList<String> lst=new ArrayList<String>(); | |||
String s = API.api.cppcms_capi_session_get_first_key(d); | |||
while(s!=null) { | |||
lst.add(s); | |||
s=API.api.cppcms_capi_session_get_next_key(d); | |||
} | |||
check(); | |||
return lst.toArray(new String[lst.size()]); | |||
} | |||
public String getCSRFToken() | |||
{ | |||
String r = API.api.cppcms_capi_session_get_csrf_token(d); | |||
check(); | |||
return r; | |||
} | |||
public void set(String key,String value) | |||
{ | |||
API.api.cppcms_capi_session_set(d,key,value); | |||
check(); | |||
} | |||
public String get(String key) | |||
{ | |||
String r = API.api.cppcms_capi_session_get(d,key); | |||
check(); | |||
return r; | |||
} | |||
public void setBinary(String key,byte[] data) | |||
{ | |||
API.api.cppcms_capi_session_set_binary(d,key,data,data.length); | |||
check(); | |||
} | |||
public byte[] getBinary(String key) | |||
{ | |||
if(!isSet(key)) | |||
return null; | |||
int len=API.api.cppcms_capi_session_get_binary_len(d,key); | |||
check(); | |||
byte[] r = new byte[len]; | |||
len=API.api.cppcms_capi_session_get_binary(d,key,r,len); | |||
check(); | |||
return r; | |||
} | |||
public void resetSession() | |||
{ | |||
API.api.cppcms_capi_session_reset_session(d); | |||
check(); | |||
} | |||
public void setDefaultAge() | |||
{ | |||
API.api.cppcms_capi_session_set_default_age(d); | |||
check(); | |||
} | |||
public void setDefaultExpiration() | |||
{ | |||
API.api.cppcms_capi_session_set_default_expiration(d); | |||
check(); | |||
} | |||
public int getAge() | |||
{ | |||
int r =API.api.cppcms_capi_session_get_age(d); | |||
check(); | |||
return r; | |||
} | |||
public void setAge(int age) | |||
{ | |||
API.api.cppcms_capi_session_set_age(d,age); | |||
check(); | |||
} | |||
public int getExpiration() | |||
{ | |||
int r =API.api.cppcms_capi_session_get_expiration(d); | |||
check(); | |||
return r; | |||
} | |||
public void setExpiration(int exp) | |||
{ | |||
API.api.cppcms_capi_session_set_expiration(d,exp); | |||
check(); | |||
} | |||
public boolean getOnServer() | |||
{ | |||
boolean r = API.api.cppcms_capi_session_get_on_server(d) != 0; | |||
check(); | |||
return r; | |||
} | |||
public void setOnServer(boolean onServer) | |||
{ | |||
API.api.cppcms_capi_session_set_on_server(d,onServer?1:0); | |||
check(); | |||
} | |||
public String getSessionCookieName() | |||
{ | |||
String r = API.api.cppcms_capi_session_get_session_cookie_name(d); | |||
check(); | |||
return r; | |||
} | |||
public void load(String cookieValue) | |||
{ | |||
API.api.cppcms_capi_session_load(d,cookieValue); | |||
check(); | |||
} | |||
public void save() | |||
{ | |||
API.api.cppcms_capi_session_save(d); | |||
check(); | |||
} | |||
public Cookie[] getServletCookies() | |||
{ | |||
CppCMSCookie[] ccs = getCookies(); | |||
Cookie[] scs = new Cookie[ccs.length]; | |||
for(int i=0;i<ccs.length;i++) { | |||
CppCMSCookie cs=ccs[i]; | |||
Cookie c=new Cookie(cs.name,cs.value); | |||
if(!cs.path.isEmpty()) | |||
c.setPath(cs.path); | |||
if(!cs.domain.isEmpty()) | |||
c.setDomain(cs.domain); | |||
if(cs.maxAgeDefined || cs.expiresDefined) { | |||
if(cs.maxAgeDefined) { | |||
c.setMaxAge(cs.maxAge); | |||
} | |||
else { | |||
long diff = cs.expires - System.currentTimeMillis() / 1000; | |||
if(diff <= 0) | |||
c.setMaxAge(0); | |||
else | |||
c.setMaxAge((int)diff); | |||
} | |||
} | |||
c.setSecure(cs.isSecure); | |||
c.setVersion(1); | |||
scs[i]=c; | |||
} | |||
return scs; | |||
} | |||
public CppCMSCookie[] getCookies() | |||
{ | |||
ArrayList<CppCMSCookie> cookies = new ArrayList<CppCMSCookie>(); | |||
Pointer p = API.api.cppcms_capi_session_cookie_first(d); | |||
while(p!=null) { | |||
cookies.add(new CppCMSCookie(p)); | |||
p = API.api.cppcms_capi_session_cookie_next(d); | |||
} | |||
check(); | |||
return cookies.toArray(new CppCMSCookie[cookies.size()]); | |||
} | |||
public String[] getCookieHeaders() | |||
{ | |||
ArrayList<String> cookies = new ArrayList<String>(); | |||
Pointer p = API.api.cppcms_capi_session_cookie_first(d); | |||
while(p!=null) { | |||
cookies.add(API.api.cppcms_capi_cookie_header_content(p)); | |||
API.api.cppcms_capi_cookie_delete(p); | |||
p = API.api.cppcms_capi_session_cookie_next(d); | |||
} | |||
check(); | |||
return cookies.toArray(new String[cookies.size()]); | |||
} | |||
public void load(HttpServletRequest request) | |||
{ | |||
String cookieName = getSessionCookieName(); | |||
Cookie[] cookies = request.getCookies(); | |||
for(int i=0;i<cookies.length;i++) { | |||
if(cookies[i].getName().equals(cookieName)) { | |||
load(cookies[i].getValue()); | |||
return; | |||
} | |||
} | |||
load(""); | |||
} | |||
public void save(HttpServletResponse response) | |||
{ | |||
save(); | |||
String[] cookies = getCookieHeaders(); | |||
for(int i=0;i<cookies.length;i++) { | |||
response.addHeader("Set-Cookie",cookies[i]); | |||
} | |||
} | |||
} |
@@ -0,0 +1,42 @@ | |||
package com.cppcms.session; | |||
import com.sun.jna.Pointer; | |||
abstract class SessionBase { | |||
protected Pointer d; | |||
protected void finalize() | |||
{ | |||
close(); | |||
} | |||
protected void check() | |||
{ | |||
if(d==null) | |||
throw new NullPointerException("Invalid class use"); | |||
int code=API.api.cppcms_capi_error(d); | |||
if(code == 0) | |||
return; | |||
String msg = API.api.cppcms_capi_error_clear(d); | |||
switch(code) { | |||
case API.ERROR_ALLOC: | |||
throw new OutOfMemoryError(msg); | |||
case API.ERROR_INVALID_ARGUMENT: | |||
throw new IllegalArgumentException(msg); | |||
case API.ERROR_LOGIC: | |||
throw new IllegalStateException(msg); | |||
default: | |||
throw new RuntimeException(msg); | |||
} | |||
} | |||
abstract void doClose(); | |||
public void close() | |||
{ | |||
if(d!=null && API.api != null) { | |||
doClose(); | |||
d=null; | |||
} | |||
} | |||
}; |
@@ -0,0 +1,36 @@ | |||
package com.cppcms.session; | |||
import com.sun.jna.Pointer; | |||
public class SessionPool extends SessionBase { | |||
private SessionPool() | |||
{ | |||
if(API.api == null) | |||
throw new NullPointerException("API.init() wasn't called - API wasn't loaded prior to use of SessionPool"); | |||
d=API.api.cppcms_capi_session_pool_new(); | |||
} | |||
public static SessionPool openFromConfig(String file) | |||
{ | |||
SessionPool p=new SessionPool(); | |||
API.api.cppcms_capi_session_pool_init(p.d,file); | |||
p.check(); | |||
return p; | |||
} | |||
public static SessionPool openFromJson(String json) | |||
{ | |||
SessionPool p=new SessionPool(); | |||
API.api.cppcms_capi_session_pool_init_from_json(p.d,json); | |||
p.check(); | |||
return p; | |||
} | |||
public Session getSession() | |||
{ | |||
return new Session(d); | |||
} | |||
void doClose() | |||
{ | |||
API.api.cppcms_capi_session_pool_delete(d); | |||
} | |||
}; |
@@ -8,9 +8,11 @@ import types | |||
from datetime import datetime | |||
class Loader: | |||
"""The native cppcms library access API""" | |||
capi = None | |||
@classmethod | |||
def load(cls,path): | |||
"""Initialize API by loading libcppcms from the given path""" | |||
cls.capi = cdll.LoadLibrary(path); | |||
# Start there | |||
cls.SESSION_FIXED=0 | |||
@@ -124,6 +126,7 @@ class Loader: | |||
cls.capi.cppcms_capi_cookie_expires.argtypes=[ c_void_p ] | |||
cls.capi.cppcms_capi_cookie_is_secure.restype=c_int | |||
cls.capi.cppcms_capi_cookie_is_secure.argtypes=[ c_void_p ] | |||
class SessionBase: | |||
def check(self): | |||
code = Loader.capi.cppcms_capi_error(self.d) | |||
@@ -137,7 +140,9 @@ class SessionBase: | |||
raise RuntimeError(msg) | |||
class SessionPool(SessionBase): | |||
"""Pool that handles all session - should be single instance per application """ | |||
def __init__(self,config_file=None,json_text=None): | |||
"""Initialize the pool from either CppCMS configuration file or directly from JSON text""" | |||
if config_file == None and json_text == None: | |||
raise ValueError('either config_file or json_text should be provided') | |||
if config_file != None and json_text != None: | |||
@@ -156,10 +161,13 @@ class SessionPool(SessionBase): | |||
def __del__(self): | |||
Loader.capi.cppcms_capi_session_pool_delete(self.d) | |||
def session(self): | |||
"""Get session for use with request/response - thread safe method""" | |||
return Session(self) | |||
class Cookie: | |||
"""Http Cookie that is generated when session is saved""" | |||
def __init__(self,ptr): | |||
"""Internal API never use directly""" | |||
self.d=ptr | |||
def __del__(self): | |||
Loader.capi.cppcms_capi_cookie_delete(self.d) | |||
@@ -172,23 +180,40 @@ class Cookie: | |||
def domain(self): | |||
return Loader.capi.cppcms_capi_cookie_domain(self.d) | |||
def header_content(self): | |||
""" | |||
Returns a header content, i.e. stuff after Set-Cookie: | |||
for example: 'name=cppcms_session; value=I2343243252; Version=1' | |||
""" | |||
return Loader.capi.cppcms_capi_cookie_header_content(self.d) | |||
def header(self): | |||
""" | |||
returns full set cookie header, for example: | |||
'Set-Cookie: name=cppcms_session; value=I2343243252; Version=1' | |||
""" | |||
return Loader.capi.cppcms_capi_cookie_header(self.d) | |||
def path(self): | |||
return Loader.capi.cppcms_capi_cookie_path(self.d) | |||
def max_age(self): | |||
"""Returns max-age value, note check max_age_defined before using it""" | |||
return Loader.capi.cppcms_capi_cookie_max_age(self.d) | |||
def expires(self): | |||
"""Returns expires value, note check expires_defined before using it""" | |||
return Loader.capi.cppcms_capi_cookie_expires(self.d) | |||
def expires_defined(self): | |||
"""Returns if expires present in the cookie""" | |||
return Loader.capi.cppcms_capi_cookie_expires_defined(self.d) | |||
def max_age_defined(self): | |||
"""Returns if max-age present in the cookie""" | |||
return Loader.capi.cppcms_capi_cookie_max_age_defined(self.d) | |||
def is_secure(self): | |||
return Loader.capi.cppcms_capi_cookie_is_secure(self.d) | |||
class Session(SessionBase): | |||
""" | |||
Object that is used to update current CppCMS session | |||
Note once the session is loaded it can be accesses | |||
as dictionary to modify its keys and values | |||
""" | |||
def __init__(self,pool): | |||
self.d=Loader.capi.cppcms_capi_session_new() | |||
Loader.capi.cppcms_capi_session_init(self.d,pool.d) | |||
@@ -201,24 +226,30 @@ class Session(SessionBase): | |||
def __del__(self): | |||
Loader.capi.cppcms_capi_session_delete(self.d) | |||
def clear(self): | |||
"""Clear entire session""" | |||
Loader.capi.cppcms_capi_session_clear(self.d) | |||
self.check() | |||
def is_set(self,key): | |||
"""Check if key is defined""" | |||
r=Loader.capi.cppcms_capi_session_is_set(self.d,key) | |||
self.check() | |||
return r; | |||
def erase(self,key): | |||
"""Remove key from session""" | |||
Loader.capi.cppcms_capi_session_erase(self.d,key) | |||
self.check() | |||
def get_exposed(self,key): | |||
"""Check if the key's value is exposed in cookies""" | |||
r=Loader.capi.cppcms_capi_session_get_exposed(self.d,key) | |||
self.check() | |||
return r!=0; | |||
def set_exposed(self,key,v): | |||
"""Set if the key's value should be exposed in cookies""" | |||
Loader.capi.cppcms_capi_session_set_exposed(self.d,key,v) | |||
self.check() | |||
def keys(self): | |||
"""Get list of all keys""" | |||
l=[] | |||
r=Loader.capi.cppcms_capi_session_get_first_key(self.d) | |||
while r: | |||
@@ -227,6 +258,7 @@ class Session(SessionBase): | |||
self.check() | |||
return l | |||
def cookies(self): | |||
"""Get all cookies defined when the session is saved - must be called after calling save""" | |||
l=[] | |||
r=Loader.capi.cppcms_capi_session_cookie_first(self.d) | |||
while r: | |||
@@ -235,21 +267,51 @@ class Session(SessionBase): | |||
self.check() | |||
return l | |||
def get_csrf_token(self): | |||
"""Get cppcms CSRF token""" | |||
r=Loader.capi.cppcms_capi_session_get_csrf_token(self.d) | |||
self.check() | |||
return r; | |||
def get_binary(self,key): | |||
"""Get binary value as bytearray""" | |||
l=Loader.capi.cppcms_capi_session_get_binary_len(self.d,key) | |||
res = bytearray(l) | |||
res_proxy = (c_char * l).from_buffer(res); | |||
Loader.capi.cppcms_capi_session_get_binary(self.d,key,res_proxy,l) | |||
self.check() | |||
return res | |||
def set_binary(self,key,value): | |||
"""Set binary value as bytearray""" | |||
if not type(value) is bytearray: | |||
raise ValueError("value should be bytearray") | |||
value_proxy = (c_char * len(value)).from_buffer(value); | |||
Loader.capi.cppcms_capi_session_set_binary(self.d,key,value_proxy,len(value)) | |||
self.check() | |||
def get(self,key): | |||
"""Get a value for a key""" | |||
r=Loader.capi.cppcms_capi_session_get(self.d,key) | |||
self.check() | |||
return r; | |||
def set(self,key,value): | |||
"""Set a value for a key""" | |||
Loader.capi.cppcms_capi_session_set(self.d,key,value) | |||
self.check() | |||
def get_session_cookie_name(self): | |||
""" | |||
Get the name of the cookie that is used to store CppCMS session | |||
Note: the value of this cookie should be passed to load method | |||
when session is loaded | |||
""" | |||
r=Loader.capi.cppcms_capi_session_get_session_cookie_name(self.d) | |||
self.check() | |||
return r | |||
def load(self,cookie=None,django_request=None): | |||
""" | |||
Load the session directly from cookie value, the name of the cookies | |||
can be obtained by calling get_session_cookie_name() | |||
Django users can provide HttpRequest object as django_request and | |||
the cookies would be retrived automatically | |||
""" | |||
if cookie!=None: | |||
Loader.capi.cppcms_capi_session_load(self.d,cookie) | |||
elif django_request!=None: | |||
@@ -260,6 +322,13 @@ class Session(SessionBase): | |||
Loader.capi.cppcms_capi_session_load(self.d,cookie) | |||
self.check() | |||
def save(self,django_response=None): | |||
""" | |||
Save the session, after the session is saved cookies as provided by cookies() | |||
method must be set to the response | |||
Django users can provide HttpResponse object as django_response to set | |||
the cookies automatically | |||
""" | |||
Loader.capi.cppcms_capi_session_save(self.d) | |||
self.check() | |||
if django_response: | |||
@@ -300,12 +369,16 @@ class Session(SessionBase): | |||
def __private_test(): | |||
import binascii | |||
state='' | |||
p=SessionPool(sys.argv[2]) | |||
s=p.session() | |||
s.load(state) | |||
s['x']='111' | |||
s.set('y','222') | |||
binary=bytearray() | |||
binary.extend(b'\x01\x00\xFF\x7F') | |||
s.set_binary('z',binary) | |||
s.set_exposed('x',1) | |||
for k in s.keys(): | |||
print ('Got ' + k) | |||
@@ -320,6 +393,8 @@ def __private_test(): | |||
s=None | |||
s=Session(p) | |||
s.load(state) | |||
tmp=s.get_binary('z') | |||
print('Binary expected \\x01\\x00\\xFF\\x7F=' + binascii.hexlify(tmp)) | |||
s.set_exposed('x',0) | |||
s.save() | |||
print("Use operator:[] ",s['x']) | |||
@@ -1,10 +0,0 @@ | |||
#!/usr/bin/env python | |||
import os | |||
import sys | |||
if __name__ == "__main__": | |||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") | |||
from django.core.management import execute_from_command_line | |||
execute_from_command_line(sys.argv) |
@@ -1 +0,0 @@ | |||
../../../cppcms.py |
@@ -1,87 +0,0 @@ | |||
""" | |||
Django settings for mysite project. | |||
For more information on this file, see | |||
https://docs.djangoproject.com/en/1.6/topics/settings/ | |||
For the full list of settings and their values, see | |||
https://docs.djangoproject.com/en/1.6/ref/settings/ | |||
""" | |||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) | |||
import os | |||
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) | |||
# Quick-start development settings - unsuitable for production | |||
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ | |||
# SECURITY WARNING: keep the secret key used in production secret! | |||
SECRET_KEY = 'wwg!$4j8zvd-jq28wt&ziub166_sbzm&ns@=+$@dcv+j%=93&s' | |||
# SECURITY WARNING: don't run with debug turned on in production! | |||
DEBUG = True | |||
TEMPLATE_DEBUG = True | |||
ALLOWED_HOSTS = [] | |||
# Application definition | |||
INSTALLED_APPS = ( | |||
'django.contrib.admin', | |||
'django.contrib.auth', | |||
'django.contrib.contenttypes', | |||
'django.contrib.sessions', | |||
'django.contrib.messages', | |||
'django.contrib.staticfiles', | |||
) | |||
MIDDLEWARE_CLASSES = ( | |||
'django.contrib.sessions.middleware.SessionMiddleware', | |||
'django.middleware.common.CommonMiddleware', | |||
'django.middleware.csrf.CsrfViewMiddleware', | |||
'django.contrib.auth.middleware.AuthenticationMiddleware', | |||
'django.contrib.messages.middleware.MessageMiddleware', | |||
'django.middleware.clickjacking.XFrameOptionsMiddleware', | |||
) | |||
ROOT_URLCONF = 'mysite.urls' | |||
WSGI_APPLICATION = 'mysite.wsgi.application' | |||
# Database | |||
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases | |||
DATABASES = { | |||
'default': { | |||
'ENGINE': 'django.db.backends.sqlite3', | |||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), | |||
} | |||
} | |||
# Internationalization | |||
# https://docs.djangoproject.com/en/1.6/topics/i18n/ | |||
LANGUAGE_CODE = 'en-us' | |||
TIME_ZONE = 'UTC' | |||
USE_I18N = True | |||
USE_L10N = True | |||
USE_TZ = True | |||
# Static files (CSS, JavaScript, Images) | |||
# https://docs.djangoproject.com/en/1.6/howto/static-files/ | |||
STATIC_URL = '/static/' | |||
# My Config | |||
CPPCMS_LIB='libcppcms.so' | |||
CPPCMS_CONFIG='config.js' |
@@ -1,12 +0,0 @@ | |||
from django.conf.urls import patterns, include, url | |||
from django.contrib import admin | |||
admin.autodiscover() | |||
urlpatterns = patterns('', | |||
# Examples: | |||
# url(r'^$', 'mysite.views.home', name='home'), | |||
# url(r'^blog/', include('blog.urls')), | |||
url(r'^$', 'mysite.views.home', name='home'), | |||
url(r'^admin/', include(admin.site.urls)), | |||
) |
@@ -1,26 +0,0 @@ | |||
from django.http import HttpResponse | |||
from django.conf import settings | |||
import cppcms | |||
cppcms.Loader.load(settings.CPPCMS_LIB) | |||
pool=cppcms.SessionPool(settings.CPPCMS_CONFIG) | |||
def home(request): | |||
s=pool.session() | |||
s.load(django_request=request) | |||
v='Nothing' | |||
if not 'x' in s: | |||
s['x']='1' | |||
else: | |||
v=s['x'] | |||
s['x']=str(int(v)+1) | |||
response = HttpResponse() | |||
s.save(django_response=response) | |||
response['Set-Cookie']='test=xxx' | |||
response.write('<html><body><h1>Cookies</h1>') | |||
response.write('<p>value=%s</p>' % v) | |||
for key,value in request.COOKIES.iteritems(): | |||
response.write('%s=%s<br>\n' % (key,value)) | |||
response.write('</body></html>') | |||
return response |
@@ -1,14 +0,0 @@ | |||
""" | |||
WSGI config for mysite project. | |||
It exposes the WSGI callable as a module-level variable named ``application``. | |||
For more information on this file, see | |||
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ | |||
""" | |||
import os | |||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") | |||
from django.core.wsgi import get_wsgi_application | |||
application = get_wsgi_application() |