Flask nocache decorator

Flask nocache decorator.

from flask import make_response
from functools import wraps, update_wrapper
from datetime import datetime

def nocache(view):
    @wraps(view)
    def no_cache(*args, **kwargs):
        response = make_response(view(*args, **kwargs))
        response.headers['Last-Modified'] = datetime.now()
        response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
        response.headers['Pragma'] = 'no-cache'
        response.headers['Expires'] = '-1'
        return response
    return update_wrapper(no_cache, view)

Use it wisely.

from nocache import nocache

@app.route('/my_endpoint')
@nocache
def my_endpoint():
    return "Endpoint without cache"

Move Sidekiq jobs

I was looking for a way to move jobs from one high priority queue to another less prioritized in Sidekiq.

There is nothing built into Sidekiq to complete this, but obviously, you can just use Redis commands to do it.

Here is code snippet to do that.

from_queue_name = 'default'
to_queue_name = 'low'
count_block = proc { Sidekiq.redis do |conn|
  conn.llen("queue:#{from_queue_name}")
end }

while count_block.call > 0
  Sidekiq.redis do |conn|
    conn.rpoplpush "queue:#{from_queue_name}", "queue:#{to_queue_name}"
  end
end

This code snippet will move all the items from one queue to another until there are no more jobs.

Ruby on Rails Engine vs Mountable App

Full Engine

With a full engine, the parent application inherits the routes from the engine. It is not necessary to specify anything in parent_app/config/routes.rb. Specifying the gem in Gemfile is enough for the parent app to inherit the models, routes etc. The engine routes are specified as:

# new_engine/config/routes.rb 
Rails.application.routes.draw do 
  # whatever 
end

No namespacing of models, controllers, etc. These are immediately accessible to the parent application.

Split Ruby on Rails routes into multiple smaller files

One time I faced fact that my application is big enough and routes.rb look like a mess. I’ve managed that this way.

I added routes directory to application config directory and added it in autoload_paths to ensure that routes are reloaded when these files change.

# config/application.rb
config.autoload_paths << Rails.root.join('config/routes')

Then moved necessary routes to small files like this.