2017年2月

首页2017年2月
25
Feb
0

Django中的事务Transaction

源网址
https://docs.djangoproject.com/en/1.10/topics/db/transactions/

Django gives you a few ways to control how database transactions are managed.

Managing database transactions¶

Django’s default transaction behavior¶

Django’s default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a transaction is active. See below for details.

Django uses transactions or savepoints automatically to guarantee the integrity of ORM operations that require multiple queries, especially delete() and update() queries.

Django’s TestCase class also wraps each test in a transaction for performance reasons.

Tying transactions to HTTP requests¶

A common way to handle transactions on the web is to wrap each request in a transaction. Set ATOMIC_REQUESTS to True in the configuration of each database for which you want to enable this behavior.

It works like this. Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django rolls back the transaction.

You may perform subtransactions using savepoints in your view code, typically with the atomic() context manager. However, at the end of the view, either all or none of the changes will be committed.

Warning

While the simplicity of this transaction model is appealing, it also makes it inefficient when traffic increases. Opening a transaction for every view has some overhead. The impact on performance depends on the query patterns of your application and on how well your database handles locking.
Per-request transactions and streaming responses

When a view returns a StreamingHttpResponse, reading the contents of the response will often execute code to generate the content. Since the view has already returned, such code runs outside of the transaction.

Generally speaking, it isn’t advisable to write to the database while generating a streaming response, since there’s no sensible way to handle errors after starting to send the response.
In practice, this feature simply wraps every view function in the atomic() decorator described below.

Note that only the execution of your view is enclosed in the transactions. Middleware runs outside of the transaction, and so does the rendering of template responses.

When ATOMIC_REQUESTS is enabled, it’s still possible to prevent views from running in a transaction.

non_atomic_requests(using=None)[source]¶
This decorator will negate the effect of ATOMIC_REQUESTS for a given view:

from django.db import transaction

@transaction.non_atomic_requests
def my_view(request):

do_stuff()

@transaction.non_atomic_requests(using='other')
def my_other_view(request):

do_stuff_on_the_other_database()

It only works if it’s applied to the view itself.

Controlling transactions explicitly¶

Django provides a single API to control database transactions.

atomic(using=None, savepoint=True)[source]¶
Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point.

atomic is usable both as a decorator:

from django.db import transaction

@transaction.atomic
def viewfunc(request):

# This code executes inside a transaction.
do_stuff()

and as a context manager:

from django.db import transaction

def viewfunc(request):

# This code executes in autocommit mode (Django's default).
do_stuff()

with transaction.atomic():
    # This code executes inside a transaction.
    do_more_stuff()

Wrapping atomic in a try/except block allows for natural handling of integrity errors:

from django.db import IntegrityError, transaction

@transaction.atomic
def viewfunc(request):

create_parent()

try:
    with transaction.atomic():
        generate_relationships()
except IntegrityError:
    handle_exception()

add_children()

In this example, even if generate_relationships() causes a database error by breaking an integrity constraint, you can execute queries in add_children(), and the changes from create_parent() are still there. Note that any operations attempted in generate_relationships() will already have been rolled back safely when handle_exception() is called, so the exception handler can also operate on the database if necessary.

Avoid catching exceptions inside atomic!

When exiting an atomic block, Django looks at whether it’s exited normally or with an exception to determine whether to commit or roll back. If you catch and handle exceptions inside an atomic block, you may hide from Django the fact that a problem has happened. This can result in unexpected behavior.

This is mostly a concern for DatabaseError and its subclasses such as IntegrityError. After such an error, the transaction is broken and Django will perform a rollback at the end of the atomic block. If you attempt to run database queries before the rollback happens, Django will raise a TransactionManagementError. You may also encounter this behavior when an ORM-related signal handler raises an exception.

The correct way to catch database errors is around an atomic block as shown above. If necessary, add an extra atomic block for this purpose. This pattern has another advantage: it delimits explicitly which operations will be rolled back if an exception occurs.

If you catch exceptions raised by raw SQL queries, Django’s behavior is unspecified and database-dependent.
In order to guarantee atomicity, atomic disables some APIs. Attempting to commit, roll back, or change the autocommit state of the database connection within an atomic block will raise an exception.

atomic takes a using argument which should be the name of a database. If this argument isn’t provided, Django uses the "default" database.

Under the hood, Django’s transaction management code:

opens a transaction when entering the outermost atomic block;
creates a savepoint when entering an inner atomic block;
releases or rolls back to the savepoint when exiting an inner block;
commits or rolls back the transaction when exiting the outermost block.
You can disable the creation of savepoints for inner blocks by setting the savepoint argument to False. If an exception occurs, Django will perform the rollback when exiting the first parent block with a savepoint if there is one, and the outermost block otherwise. Atomicity is still guaranteed by the outer transaction. This option should only be used if the overhead of savepoints is noticeable. It has the drawback of breaking the error handling described above.

You may use atomic when autocommit is turned off. It will only use savepoints, even for the outermost block.

Performance considerations

Open transactions have a performance cost for your database server. To minimize this overhead, keep your transactions as short as possible. This is especially important if you’re using atomic() in long-running processes, outside of Django’s request / response cycle.
Autocommit¶

Why Django uses autocommit¶

In the SQL standards, each SQL query starts a transaction, unless one is already active. Such transactions must then be explicitly committed or rolled back.

This isn’t always convenient for application developers. To alleviate this problem, most databases provide an autocommit mode. When autocommit is turned on and no transaction is active, each SQL query gets wrapped in its own transaction. In other words, not only does each such query start a transaction, but the transaction also gets automatically committed or rolled back, depending on whether the query succeeded.

PEP 249, the Python Database API Specification v2.0, requires autocommit to be initially turned off. Django overrides this default and turns autocommit on.

To avoid this, you can deactivate the transaction management, but it isn’t recommended.

Deactivating transaction management¶

You can totally disable Django’s transaction management for a given database by setting AUTOCOMMIT to False in its configuration. If you do this, Django won’t enable autocommit, and won’t perform any commits. You’ll get the regular behavior of the underlying database library.

This requires you to commit explicitly every transaction, even those started by Django or by third-party libraries. Thus, this is best used in situations where you want to run your own transaction-controlling middleware or do something really strange.

Performing actions after commit¶

New in Django 1.9.
Sometimes you need to perform an action related to the current database transaction, but only if the transaction successfully commits. Examples might include a Celery task, an email notification, or a cache invalidation.

Django provides the on_commit() function to register callback functions that should be executed after a transaction is successfully committed:

on_commit(func, using=None)[source]¶
Pass any function (that takes no arguments) to on_commit():

from django.db import transaction

def do_something():

pass  # send a mail, invalidate a cache, fire off a Celery task, etc.

transaction.on_commit(do_something)
You can also wrap your function in a lambda:

transaction.on_commit(lambda: some_celery_task.delay('arg1'))
The function you pass in will be called immediately after a hypothetical database write made where on_commit() is called would be successfully committed.

If you call on_commit() while there isn’t an active transaction, the callback will be executed immediately.

If that hypothetical database write is instead rolled back (typically when an unhandled exception is raised in an atomic() block), your function will be discarded and never called.

Savepoints¶

Savepoints (i.e. nested atomic() blocks) are handled correctly. That is, an on_commit() callable registered after a savepoint (in a nested atomic() block) will be called after the outer transaction is committed, but not if a rollback to that savepoint or any previous savepoint occurred during the transaction:

with transaction.atomic(): # Outer atomic, start a new transaction

transaction.on_commit(foo)

with transaction.atomic():  # Inner atomic block, create a savepoint
    transaction.on_commit(bar)

foo() and then bar() will be called when leaving the outermost block

On the other hand, when a savepoint is rolled back (due to an exception being raised), the inner callable will not be called:

with transaction.atomic(): # Outer atomic, start a new transaction

transaction.on_commit(foo)

try:
    with transaction.atomic():  # Inner atomic block, create a savepoint
        transaction.on_commit(bar)
        raise SomeError()  # Raising an exception - abort the savepoint
except SomeError:
    pass

foo() will be called, but not bar()

Order of execution¶

On-commit functions for a given transaction are executed in the order they were registered.

Exception handling¶

If one on-commit function within a given transaction raises an uncaught exception, no later registered functions in that same transaction will run. This is, of course, the same behavior as if you’d executed the functions sequentially yourself without on_commit().

Timing of execution¶

Your callbacks are executed after a successful commit, so a failure in a callback will not cause the transaction to roll back. They are executed conditionally upon the success of the transaction, but they are not part of the transaction. For the intended use cases (mail notifications, Celery tasks, etc.), this should be fine. If it’s not (if your follow-up action is so critical that its failure should mean the failure of the transaction itself), then you don’t want to use the on_commit() hook. Instead, you may want two-phase commit such as the psycopg Two-Phase Commit protocol support and the optional Two-Phase Commit Extensions in the Python DB-API specification.

Callbacks are not run until autocommit is restored on the connection following the commit (because otherwise any queries done in a callback would open an implicit transaction, preventing the connection from going back into autocommit mode).

When in autocommit mode and outside of an atomic() block, the function will run immediately, not on commit.

On-commit functions only work with autocommit mode and the atomic() (or ATOMIC_REQUESTS) transaction API. Calling on_commit() when autocommit is disabled and you are not within an atomic block will result in an error.

Use in tests¶

Django’s TestCase class wraps each test in a transaction and rolls back that transaction after each test, in order to provide test isolation. This means that no transaction is ever actually committed, thus your on_commit() callbacks will never be run. If you need to test the results of an on_commit() callback, use a TransactionTestCase instead.

Why no rollback hook?¶

A rollback hook is harder to implement robustly than a commit hook, since a variety of things can cause an implicit rollback.

For instance, if your database connection is dropped because your process was killed without a chance to shut down gracefully, your rollback hook will never run.

The solution is simple: instead of doing something during the atomic block (transaction) and then undoing it if the transaction fails, use on_commit() to delay doing it in the first place until after the transaction succeeds. It’s a lot easier to undo something you never did in the first place!

Low-level APIs¶

Warning

Always prefer atomic() if possible at all. It accounts for the idiosyncrasies of each database and prevents invalid operations.

The low level APIs are only useful if you’re implementing your own transaction management.
Autocommit¶

Django provides a straightforward API in the django.db.transaction module to manage the autocommit state of each database connection.

get_autocommit(using=None)[source]¶
set_autocommit(autocommit, using=None)[source]¶
These functions take a using argument which should be the name of a database. If it isn’t provided, Django uses the "default" database.

Autocommit is initially turned on. If you turn it off, it’s your responsibility to restore it.

Once you turn autocommit off, you get the default behavior of your database adapter, and Django won’t help you. Although that behavior is specified in PEP 249, implementations of adapters aren’t always consistent with one another. Review the documentation of the adapter you’re using carefully.

You must ensure that no transaction is active, usually by issuing a commit() or a rollback(), before turning autocommit back on.

Django will refuse to turn autocommit off when an atomic() block is active, because that would break atomicity.

Transactions¶

A transaction is an atomic set of database queries. Even if your program crashes, the database guarantees that either all the changes will be applied, or none of them.

Django doesn’t provide an API to start a transaction. The expected way to start a transaction is to disable autocommit with set_autocommit().

Once you’re in a transaction, you can choose either to apply the changes you’ve performed until this point with commit(), or to cancel them with rollback(). These functions are defined in django.db.transaction.

commit(using=None)[source]¶
rollback(using=None)[source]¶
These functions take a using argument which should be the name of a database. If it isn’t provided, Django uses the "default" database.

Django will refuse to commit or to rollback when an atomic() block is active, because that would break atomicity.

Savepoints¶

A savepoint is a marker within a transaction that enables you to roll back part of a transaction, rather than the full transaction. Savepoints are available with the SQLite (≥ 3.6.8), PostgreSQL, Oracle and MySQL (when using the InnoDB storage engine) backends. Other backends provide the savepoint functions, but they’re empty operations – they don’t actually do anything.

Savepoints aren’t especially useful if you are using autocommit, the default behavior of Django. However, once you open a transaction with atomic(), you build up a series of database operations awaiting a commit or rollback. If you issue a rollback, the entire transaction is rolled back. Savepoints provide the ability to perform a fine-grained rollback, rather than the full rollback that would be performed by transaction.rollback().

When the atomic() decorator is nested, it creates a savepoint to allow partial commit or rollback. You’re strongly encouraged to use atomic() rather than the functions described below, but they’re still part of the public API, and there’s no plan to deprecate them.

Each of these functions takes a using argument which should be the name of a database for which the behavior applies. If no using argument is provided then the "default" database is used.

Savepoints are controlled by three functions in django.db.transaction:

savepoint(using=None)[source]¶
Creates a new savepoint. This marks a point in the transaction that is known to be in a “good” state. Returns the savepoint ID (sid).

savepoint_commit(sid, using=None)[source]¶
Releases savepoint sid. The changes performed since the savepoint was created become part of the transaction.

savepoint_rollback(sid, using=None)[source]¶
Rolls back the transaction to savepoint sid.

These functions do nothing if savepoints aren’t supported or if the database is in autocommit mode.

In addition, there’s a utility function:

clean_savepoints(using=None)[source]¶
Resets the counter used to generate unique savepoint IDs.

The following example demonstrates the use of savepoints:

from django.db import transaction

open a transaction

@transaction.atomic
def viewfunc(request):

a.save()
# transaction now contains a.save()

sid = transaction.savepoint()

b.save()
# transaction now contains a.save() and b.save()

if want_to_keep_b:
    transaction.savepoint_commit(sid)
    # open transaction still contains a.save() and b.save()
else:
    transaction.savepoint_rollback(sid)
    # open transaction now contains only a.save()

Savepoints may be used to recover from a database error by performing a partial rollback. If you’re doing this inside an atomic() block, the entire block will still be rolled back, because it doesn’t know you’ve handled the situation at a lower level! To prevent this, you can control the rollback behavior with the following functions.

get_rollback(using=None)[source]¶
set_rollback(rollback, using=None)[source]¶
Setting the rollback flag to True forces a rollback when exiting the innermost atomic block. This may be useful to trigger a rollback without raising an exception.

Setting it to False prevents such a rollback. Before doing that, make sure you’ve rolled back the transaction to a known-good savepoint within the current atomic block! Otherwise you’re breaking atomicity and data corruption may occur.

Database-specific notes¶

Savepoints in SQLite¶

While SQLite ≥ 3.6.8 supports savepoints, a flaw in the design of the sqlite3 module makes them hardly usable.

When autocommit is enabled, savepoints don’t make sense. When it’s disabled, sqlite3 commits implicitly before savepoint statements. (In fact, it commits before any statement other than SELECT, INSERT, UPDATE, DELETE and REPLACE.) This bug has two consequences:

The low level APIs for savepoints are only usable inside a transaction ie. inside an atomic() block.
It’s impossible to use atomic() when autocommit is turned off.
Transactions in MySQL¶

If you’re using MySQL, your tables may or may not support transactions; it depends on your MySQL version and the table types you’re using. (By “table types,” we mean something like “InnoDB” or “MyISAM”.) MySQL transaction peculiarities are outside the scope of this article, but the MySQL site has information on MySQL transactions.

If your MySQL setup does not support transactions, then Django will always function in autocommit mode: statements will be executed and committed as soon as they’re called. If your MySQL setup does support transactions, Django will handle transactions as explained in this document.

Handling exceptions within PostgreSQL transactions¶

Note

This section is relevant only if you’re implementing your own transaction management. This problem cannot occur in Django’s default mode and atomic() handles it automatically.
Inside a transaction, when a call to a PostgreSQL cursor raises an exception (typically IntegrityError), all subsequent SQL in the same transaction will fail with the error “current transaction is aborted, queries ignored until end of transaction block”. While simple use of save() is unlikely to raise an exception in PostgreSQL, there are more advanced usage patterns which might, such as saving objects with unique fields, saving using the force_insert/force_update flag, or invoking custom SQL.

There are several ways to recover from this sort of error.

Transaction rollback¶

The first option is to roll back the entire transaction. For example:

a.save() # Succeeds, but may be undone by transaction rollback
try:

b.save() # Could throw exception

except IntegrityError:

transaction.rollback()

c.save() # Succeeds, but a.save() may have been undone
Calling transaction.rollback() rolls back the entire transaction. Any uncommitted database operations will be lost. In this example, the changes made by a.save() would be lost, even though that operation raised no error itself.

Savepoint rollback¶

You can use savepoints to control the extent of a rollback. Before performing a database operation that could fail, you can set or update the savepoint; that way, if the operation fails, you can roll back the single offending operation, rather than the entire transaction. For example:

a.save() # Succeeds, and never undone by savepoint rollback
sid = transaction.savepoint()
try:

b.save() # Could throw exception
transaction.savepoint_commit(sid)

except IntegrityError:

transaction.savepoint_rollback(sid)

c.save() # Succeeds, and a.save() is never undone
In this example, a.save() will not be undone in the case where b.save() raises an exception.

Django默认的事务行为
默认情况下,在Django中事务是自动提交的。当我们运行Django内置的模板修改函数时,例如调用model.save()或model.delete()时,事务将被立即提交。这种机制和数据库的自动提交事务机制类似。记住这里没有默认的回滚机制。

在HTTP请求上加事务
对于Web请求,Django官方推荐使用中件间TransactionMiddleware来处理请求和响应中的事务。它的工作原理是这样的:当一个请求到来时,Django开始一个事务,如果响应没有出错,Django提交这期间所有的事务,如果view中的函数抛出异常,那么Django会回滚这之间的事务。
为了实现这个特性,需要在MIDDLEWARE_CLASSES setting中添加TransactionMiddleware:

MIDDLEWARE_CLASSES = (

'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',

)

顺序很重要,TransactionMiddleware中间件会将置于其后的中间件都包含在事务的范围之中(用于缓存的中间件除外,他们不受影响,例如CacheMiddleware,UpdateCacheMiddleware和FetchFromCacheMiddleware)。
另外需要注意的是,TransactionMiddleware只会影响DATABASES设置中的默认的数据库,对于其它的数据库,如果我们实现事务控制的话只能用别的方案了。

在View中实现事务控制
如果想在更细粒度的条件下(例如在一个view函数中)控制事务,我们可以使用django.db.transaction。有两种用法:
1.使用装饰器
from django.db import transaction

@transaction.commit_on_success
def viewfunc(request):

# ...
# this code executes inside a transaction

...

2.使用context manager
from django.db import transaction

def viewfunc(request):

# ...
# this code executes using default transaction management
# ...

with transaction.commit_on_success():
    # ...
    # this code executes inside a transaction
    # ...

这两种方法都可以正常工作。不过如果使用的Python版本为2.5并且要使用with语法的话,还需加一句
from future import with_statement。
所以为了最大的兼容性,下面的示例使用装饰器来实现事务。
autocommit()
使用autocommit装饰器可以将view函数中的事务还原成Django默认的自动提交模式,无视全局事务的设置。
示例:
from django.db import transaction

@transaction.autocommit
def viewfunc(request):

....

@transaction.autocommit(using="my_other_database")
def viewfunc2(request):
....

commit_on_success()
顾名思义,view函数成功则提交事务,否则回滚。用法同上。
commit_manually()
告诉Django我们将自己控制函数中的事务处理。并且要注意,如果在视图函数中改变了数据库的数据并且没有调用commit() 或rollback(),那么将抛出TransactionManagementError异常。
示例:
from django.db import transaction

@transaction.commit_manually
def viewfunc(request):

...
# You can commit/rollback however and whenever you want
transaction.commit()
...

# But you've got to remember to do it yourself!
try:
    ...
except:
    transaction.rollback()
else:
    transaction.commit()

@transaction.commit_manually(using="my_other_database")
def viewfunc2(request):
....

24
Feb
0

django中使用原生sql

在Django中使用原生Sql主要有以下几种方式:
一:extra:结果集修改器,一种提供额外查询参数的机制
二:raw:执行原始sql并返回模型实例
三:直接执行自定义Sql
(
这种方式完全不依赖model,前两种还是要依赖于model
)

实例:
使用extra:
1:Book.objects.filter(publisher__name='广东人员出版社').extra(where=['price>50'])
Book.objects.filter(publisher__name='广东人员出版社',price__gt=50)

2:Book.objects.extra(select={'count':'select count(*) from hello_Book'})

使用raw:
Book.objects.raw('select * from hello_Book')

自定义sql:
Book.objects.raw("insert into hello_author(name) values('测试')")
rawQuerySet为惰性查询,只有在使用时生会真正执行

执行自定义sql:
from django.db import connection
cursor=connection.cursor()

插入操作

cursor.execute("insert into hello_author(name) values('郭敬明')")

更新操作

cursor.execute('update hello_author set name='abc' where name='bcd'')

删除操作

cursor.execute('delete from hello_author where name='abc'')

查询操作

cursor.execute('select * from hello_author')
raw=cursor.fetchone() #返回结果行游标直读向前,读取一条
cursor.fetchall() #读取所有

23
Feb
0

django中ajax使用POST时使用csrf_token

django对POST请求需要csrf_token验证,后端会检测前端发过来的token,如果有问题可以会出现403Forbidden的错误。

这个token是由后端在页面GET请求页面文件的时候就放进去的,可以在模板中使用{% csrf_token %},例如表单的POST请求就可以这个做,会生成一个隐藏的表单域,带有后端响应页面时塞进来的随机生成的token值。而ajax的请求可以在HTTP header里把这个值放进去,后端需要响应并返回页面文件时塞进cookie,以便前端可以拿到这个值然后放到Header里再进行POST请求。

对于POST请求,要想前端有token数据,需要几个修饰方法decorator method

from django.views.decorators.csrf import csrf_protect

from django.views.decorators.csrf import requires_csrf_token

from django.views.decorators.csrf import ensure_csrf_cookie
这里使用的是这个,前端可以从cookie里拿到token值
使用的时候在相应的view或者方法上加上
@ensure_csrf_cookie
例如:
from django.views.decorators.csrf import requires_csrf_token
from django.shortcuts import render

@requires_csrf_token
def my_view(request):

c = {}
c.update(csrf(request))
return HttpResponse("value", c)

而要使POST不会检测token可以使用
@csrf_exempt
对于ajax ,前端需要获取token
Javascipt

function getCookie(name) {

            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        function loaddata()
        {
            var csrftoken = getCookie('csrftoken');
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    str = xmlhttp.responseText;
                    alert(str);
                }
            }
            xmlhttp.open("POST","ajax/",true);
            xmlhttp.setRequestHeader('X-CSRFToken',csrftoken)
            xmlhttp.send();
        }

要先open(),再setRequestheader(),然后再send()
JQuery 来自官方文档

function csrfSafeMethod(method) {

// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));

}
function sameOrigin(url) {

// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
    (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
    // or any other URL that isn't scheme relative or absolute i.e relative.
    !(/^(\/\/|http:|https:).*/.test(url));

}
$.ajaxSetup({

beforeSend: function(xhr, settings) {
    if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
        // Send the token to same-origin, relative URLs only.
        // Send the token only if the method warrants CSRF protection
        // Using the CSRFToken value acquired earlier
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
}

});

//////////////////使用CSRF成功的例子 执行AJAX前执行如下代码///////////////////////////
function csrfSafeMethod(method) {

// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));

}
function sameOrigin(url) {

// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
    (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
    // or any other URL that isn't scheme relative or absolute i.e relative.
    !(/^(\/\/|http:|https:).*/.test(url));

}
function getCookie(name) {

var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
         var cookie = jQuery.trim(cookies[i]);
         // Does this cookie string begin with the name we want?
         if (cookie.substring(0, name.length + 1) == (name + '=')) {
             cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
             break;
         }
     }
}
return cookieValue;

}
$.ajaxSetup({

beforeSend: function(xhr, settings) {
    if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
        // Send the token to same-origin, relative URLs only.
        // Send the token only if the method warrants CSRF protection
        // Using the CSRFToken value acquired earlier
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
}

});
csrftoken = getCookie('csrftoken');
$.ajaxSetup({

beforeSend: function(xhr, settings) {
    if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
}

});

19
Feb
0

js操作JSON方法

JSON字符串:
var str1 = '{ "name": "cxh", "sex": "man" }';
JSON对象:
var str2 = { "name": "cxh", "sex": "man" };

将JSON对象转化为JSON字符:
var last=obj.toJSONString(); //
或者
var last=JSON.stringify(obj);

由JSON字符串转换为JSON对象:
var obj = str.parseJSON(); //
或者
var obj = JSON.parse(str);

18
Feb
0

python枚举实现(未实现反推字符串)

第一种方法

class Directions:

up = 0
down = 1
left = 2
right =3

print Directions.down

可以加入CONST实现方法,实现不可更改的值,更完美

第二种

dirUp, dirDown, dirLeft, dirRight = range(4)
print dirDown

第三种

def enum(**enums):

return type('Enum', (), enums)

Numbers = enum(ONE=1, TWO=2, THREE='three')

反推字符串方法 怎么搞定呢