Posts

Showing posts from November, 2015

Set the default session expired time in Django

In Django, you can set the expired time of session by this setting, for example after 10 minutes: SESSION_COOKIE_AGE = 10 * 60 In addition, if you want the session will be expired when the user closes her browser, you can set: SESSION_EXPIRE_AT_BROWSER_CLOSE = True

Capture and save celery tasks information into the database in your Django project

Image
In my experience, It's a good idea that you can store the celery tasks information into the database so you can have a better idea about what going in the background without touching the enormous logs pool. Here is how easy it is to do it: 1. In your Django project's settings.py: CELERY_RESULT_BACKEND = 'db+mysql://mydbuser:mydbpasswd@localhost/mydb' CELERY_TRACK_STARTED = True CELERY_SEND_TASK_SENT_EVENT = True 2. Along side with celeryd, you need to run the celerycam app: (venv)$ ./manage.py celerycam 3. And then in your Django admin's dashboard, go to tasks under Djcelery section and enjoy the greatness:

Manage your RabbitMQ message broker via the web interface

Image
Yes, you heard it right. There's a web interface to manage/monitor your RabbitMQ message broker. And it's buit-in. You just need to enable it: $ sudo rabbitmq-plugins enable rabbitmq_management $ sudo service rabbitmq-server restart Then use your administrator account to login into the web interface at http://localhost:15672 If you don't set up your administrator account yes, you can create it by: $ sudo rabbitmqctl add_user myadmin mypasswd $ sudo rabbitmqctl set_user_tags myadmin administrator $ sudo rabbitmqctl set_permissions -p / myadmin ".*" ".*" ".*" You will see the gorgeous dashboard: References: [0] http://www.rabbitmq.com/management.html [1] http://stackoverflow.com/questions/22850546/cant-access-rabbitmq-web-management-interface-after-fresh-install

Manipulate MS SQL database using SQLAlchemy

There are many chances that you have to communicate with your MS SQL server using your python app. Here is a simple setup in a Ubuntu (14.04 x64) server that you can apply to your project: 1. Install FreeTDS driver and ODBC: $ sudo apt-get install tdsodbc You may also want to install the FreeTDS testing tool tsql: $ sudo apt-get install freetds-bin 2. Configure FreeTDS driver: $ sudo nano /etc/freetds/freetds.conf Add your MS SQL info block: ... [ yourmssql ]         host = your.mssql.com         Port = 1433         tds version = 4.2 3. Setup ODBC: $ sudo nano /etc/odbcinst.ini Add the following FreeTDS info: [ FreeTDS ] Description=FreeTDS Driver v0.91 Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup=/usr/lib/x86_64-linux-gnu/odbc/libtdsS.so fileusage=1 dontdlclose=1 UsageCount=1 client charset = utf-8 $ sudo nano /etc/odbc.ini Add these following lines: [yourdsn] Driver = FreeTDS Description = ODBC conn

Saving image to Django's ImageField programmatically

In order to save an image to a Django model's ImageField programmatically instead of using the upload form, you can do as following example: 0. Assuming you have this model: models.py ... class MyModel (models.Model):     image = models.ImageField(upload_to='path') ... 1. First, upload your image to the upload_to folder defined in your  settings.py : ... UPLOAD_TO = 'photos' ... 2. In  views.py or any utility module: from django.conf import settings ... layout = MyModel() layout.image = "%s/image.png" % settings.UPLOAD_TO layout.save() Reference:   http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-django-imagefield

Update Moodle user's photo programmatically

In some cases, being able to update the moodle user's photo using command line instead of the web interface is pretty helpful. Here is the PHP snippet I wrote which will accomplish that: Notes: 1. The photo was name after the user's idnumber. You can use the username instead. 2. Need to run the script as root or sudo.

Running sudo without entering the password

In my experience, If you want to run a command with sudo privileges but don't want to bother entering the password, visudo is the best way to go. For example you want to run this command when log-in as user youruser (a sudoer): sudo php /path/to/your/script.php some_params Note that the param may be different. 1. First, running this as root: # visudo 2. Then add the following line: youruser ALL=(root) NOPASSWD: /usr/bin/php /path/to/your/script.php * 3. Save and exit the editor

Remove all celery tasks in Django

To delete all the celery tasks in Django, run the following command: (venv): ./manage.py celery purge

Get user by username (or any other attributes) in Moodle

You can do as the following snippet to get the user object by username (or any other attributes) #!/usr/bin/php <?php define('CLI_SCRIPT', true); require_once('../config.php'); global $DB; $user = $DB->get_record('user', array('username'=>'myusername'));                                                              print_r($user); exit; ?> Reference:   https://docs.moodle.org/dev/Data_manipulation_API

A song

I guess You don't know (M Signal) I met you, loved you and hurt by that love Just looking at you without being beside you, I’m a fool. When you cried, I cried. When you smiled, I smiled. Like a child, just following you whatever you do, I’m a fool. I love you but you can’t hear it I love you but you don’t know it I shed teardrops in my heart but you don’t see it I call out your name but you  can’t hear it. You are the only one for me but you don’t know it. My love is blind, my love is poignant, and I can’t do that. Just turn around and I’m right here behind you. When you’re tired of someone else’s  love, hurt by someone else’s love Just turn around once. I love you but you can’t hear it I love you but you don’t know it I shed teardrops in my heart but you don’t see it I call out your name but you can’t hear it. You are the only one but you don’t know it. My love is blind, my love is poignant, and I can’t do that. Today I call you a thousand times.. Even though you can’t hear it

ImageField overwrite image file with same name

The default behavior of the Django ImageField when you upload a new image has the same name with an existing image Django will add suffix to that new one: existingname_<somesuffix>.JPG But if the image names are identical and represent each object in the database (named after the object's pk), you don't want to have that suffix added. You just want to remove the existing one with the new photo. If that the case, you can define your storage class and assign to the ImageField in models.py like the following example: 1. Create a file name storage.py and put it in the same place with settings.py: from django.core.files.storage import FileSystemStorage from django.conf import settings import os class OverwriteStorage( FileSystemStorage):     def get_available_name(self, name):         """Returns a filename that's free on the target storage system, and         available for new content to be written to.         Found at http://djangosnippet

Django ImageField rename file on upload

By default Django keeps the original name of the uploaded file but more than likely you will want to rename it to something else (like the object's id). Luckily, with ImageField or FileField of Django forms, you can assign a callable function to the upload_to parameter to do the renaming. For example: from django.db import models from django.utils import timezone import os from uuid import uuid4 def path_and_rename (instance, filename):     upload_to = 'photos'     ext = filename.split('.')[-1]     # get filename     if instance.pk:         filename = '{}.{}'.format(instance.pk, ext)     else:         # set filename as random string         filename = '{}.{}'.format(uuid4().hex, ext)     # return the whole path to the file     return os.path.join(upload_to, filename) class CardInfo (models.Model):     id_number = models.CharField(max_length=6, primary_key=True)     name = models.CharField(max_length=255)     photo = models.Ima

Quote of the day

"Việc khó nhất trên đời không phải là giỏi lấy tiền của người khác để nhét đầy túi của mình, mà là giỏi dùng suy nghĩ của chính mình để nhét vào đầu người khác." ~ Pinocchio , A Drama by SBS.